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?

Link to comment
Share on other sites

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

Link to comment
Share on other sites

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;

Link to comment
Share on other sites

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?

Link to comment
Share on other sites

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

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.