tags:

views:

499

answers:

3

Hi all,
I have a select box that shows 3 options: option1, option2, option3. When a user hits submit, then in $_POST I do have the value selected. Is there an easy way to redisplay the select box with the chosen option highlighted WITHOUT it being repeated in the options?

In other words, if option2 is selected and submit is clicked, the page should display again with option2 selected, and option1 and option 3 underneath.

Thanks.

A: 

When you generate the select box, use the POST data (if available) to pick the item that's selected (and/or to sort the items).

Kind of like:

if($_POST["optval"] == $opt) $sel = "selected='selected'"; else $sel = "";
print "<option value='$opt' " . $sel . ">$opt</option>";

Naturally you'd want to verify that the POST data is valid and that it exists (isset). Assuming of course that you generate your select box from data accessible by PHP, rather than statically define it.

Matthew Iselin
Updated to remove the horrendous fail at PHP.
Matthew Iselin
+1  A: 

Create your options like this.

$options = array("optionvalue" => "Option Name");

foreach($options as $value => $name)
{
    if(isset($_POST['select_box']))
    {
        if($_POST['select_box'] == $value)
        {
            echo '<option selected="selected" value="'.$value.'">'.$name.'</option>';
            continue;
        }
    }
    echo '<option value="'.$value.'">'.$name.'</option>';
}
Chacha102
I'm pretty sure you effed that up. You wrote selected=selected on all your branches....why are there even 3 branches?! It's either selected or it's not.
Mark
This is a little inefficient lines-of-code-wise. @Jordan S. Jones' solution is a bit better in that regard.
ceejayoz
I fixed it.
Chacha102
It also makes more sense to have `$value => $name` rather than the way you have it.
Mark
I think the foreach $value => $name needs to be $name => $value, but thanks
Michael
+2  A: 
<?php

    $arrValues = array(...);

    $selectedValue = (isset ($_POST['selectName']) ? $_POST['selectName'] : "");

?>
<select name="selectName">
<?php
    for ($i = 0; $i < count($arrValues); $i++)
    {
     $opts = ($arrValues[$i] == $selectedValue) ? ' selected="selected"': '';
     echo '<option value="' . $arrValues[$i] . '"' . $opts . '>' . $arrValues[$i] . '</option>';
    }
?>
</select>
Jordan S. Jones
You shouldn't use `count($arr)` in a for loop like that. It will be recomputed each iteration. Why not just use a foreach? It's more concise.
Mark
That is a good point Mark, I could have said for ($i = 0, $size = count($arrValues); ...) or use a foreach. I didn't because I've been back and forth in C#, Java, PHP, and Javascript today, and didn't want to think about the syntax (read: I was being lazy). :)
Jordan S. Jones
Thanks for the response, I ended up taking Chacha's + your ? :
Michael