Jump to content

[SOLVED] How to include a selected tag from a foreach select tag dropdown list?


kee2ka4

Recommended Posts

Hello Peeps,

 

I have a question regarding the select tag in a form. I have a php ForEach loop that loops throught a database an gets the value and the name of the select tags for the dropdown list. Here is the code:

<select name="c">
     	<option value="">ALL</option>
        <?php foreach($catList as $catName): ?>
	<option value="<?php echo $catName['id'] ?>"><?php echo $catName['name'] ?></option>
        <?php endforeach; ?>
</select>

 

I needed to include a selected = "" tag if the $catName['id'] == $_GET['c']; I am not sure how to code this in the loop. Can anyone plz guid me on this.

 

Thanks,

Zub

Link to comment
Share on other sites

Change

        <?php foreach($catList as $catName): ?>
	<option value="<?php echo $catName['id'] ?>"><?php echo $catName['name'] ?></option>
        <?php endforeach; ?>

to

        <?php foreach($catList as $catName): ?>
	<option value="<?php echo $catName['id'] ?>"<?php (($catName['id'] == $_GET['c']) ? 'selected="selected"' : null) ?>><?php echo $catName['name'] ?></option>
        <?php endforeach; ?>

Link to comment
Share on other sites

Hi, Thanks for your msg. I changed the code but it doesn't seem to work! Do I also tried added

echo 'selected="selected"'

but get an error so removed it.

 

The dropdown works fine but the selected tag doesn't get added. Also the $_GET['c'] contains an id because I echo out the value of it at the top. Any Idea why it doesn't work?

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.