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

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; ?>

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?

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.