Jump to content

PHP and OPTION & SELECT


Mundo

Recommended Posts

I'm a little stuck...

 

Say the URL is http://ilovecars.com/index.php?car=Volvo

 

and I have a loop which outputs my options such as:

<option value="$car">$car</option>

 

I want to have the car which is selected (in this case volvo) selected in the list. For example:

<option value="$car" selected="selected">$car</option>

 

Obviously I don't want "selected" on the rest of the listbox...

 

How could I get PHP to do that?

 

Many thanks for any help

Link to comment
https://forums.phpfreaks.com/topic/208283-php-and-option-select/
Share on other sites

Inside your loop where you print out all the <option>s, check if $car is equal to $_GET['car'] and, if so, print out selected="selected" in your tag otherwise print it out without.

 

if($car == $_GET['car'])
{
echo "<option value=\"$car\" selected=\"selected\">$car</option>";
} else {
echo "<option value=\"$car\">$car</option>";
}

Personally I'd be more inclined to do something like:

 

$car  = $_GET['car'];
$cars = array('Volvo', 'Ford', 'Nissan', 'Toyota');

$select = '<select name="cars">';
foreach ($cars as $key => $val) {
  $select .= '<option value="'. $val .'"';
  if (isset($car) && $car == $val) {
    $select .= ' selected="selected"';
  }
  $select .= '>'. $val .'</option>';
}
$select .= '</select>';

echo $select;
?>

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.