Jump to content

Programatically selecting an item in a list


grs5211

Recommended Posts

I have built a list with this code:

<select id="moduleBox" name="selModule" style="align: center;" onChange="insertCode()">

    <option value="A">Apple</option>

    <option value="L">Lemon</option>

    <option value="P">Peach</option>

    </select>

 

I have brought over a query string variable from another page which has the value I want selected in ="selModule".

Lets say the $_REQUEST("value") = "Lemon"

How do I show this as the selected value in the listbox?

Off the top of my head you should be using $_GET['value'] instead (security thing). Then all you have to do is write an if/else like...

 

<?php
if ($_GET['value'] == $option_value) {
  $selected = 'selected="selected"';
} else {
  $selected = '';
}

echo '<option value="whatever" ' . $selected . '>Label</option>';
?>

Off the top of my head you should be using $_GET['value'] instead (security thing). Then all you have to do is write an if/else like...

 

<?php
if ($_GET['value'] == $option_value) {
  $selected = 'selected="selected"';
} else {
  $selected = '';
}

echo '<option value="whatever" ' . $selected . '>Label</option>';
?>

 

Just to shorten that, to make it look a little nicer:

 

$selected = ($_GET['value'] == $option_value) ? 'selected="selected" : NULL;

I get what you are saying here, but this assumes there is a processing loop to go through, which there is not.

Lets say we are 'hard coding' every fruit known(thats a lot). We can't use the code at every <OPTION> line to decide if that is the one we want selected.

Should we not do this after the <SELECT> is built?

try

<?php
$options = '<select id="moduleBox" name="selModule" style="align: center;" onChange="insertCode()">
     <option value="A">Apple</option>
     <option value="L">Lemon</option>
     <option value="P">Peach</option>
     </select>';
$options = str_replace('value="'.$_REQUEST['value'].'"', 'value="'.$_REQUEST['value'].'" selected="selected" ', $options);
echo $options;
?>

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.