Vincent Russo
Vincent Russo

Reputation: 1089

HTML Select Form Keep Drop Down Values PHP

Say I have a form that contains a drop-down list populated by values stored in my database:

<form action="" method="POST">
    <select name="item_select">
    <?php 
    $query = "SELECT * FROM my_table ORDER BY name";
    $result = mysql_query($query);
    while ($row = mysql_fetch_object($result)) { 
    ?>
        <option value=<?php echo $row->id; ?> > <?php echo $row->name; ?></option>
        <?php }// end while?>
    </select>
    <br /><br />
    <input name="action_1" type="submit" value="Action 1" />
    <input name="action_2" type="submit" value="Action 2" />
</form> 

This all works fine, but I have a minor aesthetic issue I'd like to see if I can fix. Specifically every time I submit the form, the drop-down list selects the first item in the list, no matter which one I select. For instance.

List:
Item1 (selected)
Item2

I selected Item2 and submit the form, after the page submits it is still

List:
Item1 (selected)
Item2

Is there a way to have the drop-down "remember" which item was selected? For instance the desired effect after submitting the form for Item2 should be.

List:
Item1
Item2 (selected)

Upvotes: 0

Views: 2918

Answers (3)

Ghazanfar Mir
Ghazanfar Mir

Reputation: 3543

Try the following:

<option value="<?php echo $row->id ?>" <?php echo $row->id == $_POST['item_select'] ? "selected='selected'" : "" ?> ><?php echo $row->name ?></option>

Upvotes: 0

SpaceBeers
SpaceBeers

Reputation: 13947

Personally I'd have a function that does all this for you for select, checkbox and radio inputs. But only if you're going to need to do this multiple times. For example:

function checker($type, $positive, $value) {
    if ($type == 'radio') {
        if ($positive == $value) {
            $bool = 'CHECKED';
        }
    }

    if ($type == 'checkbox') {
        if ($positive == $value) {
            $bool = 'CHECKED';
        }
    }

    if ($type == 'select') {
        if ($positive == $value) {
            $bool = 'SELECTED';
        }
    }

    return $bool;
}

Use as follows:

<select name="item_select">
    <?php 
    $query = "SELECT * FROM my_table ORDER BY name";
    $result = mysql_query($query);
    while ($row = mysql_fetch_object($result)) { 
    ?>
        <option value=<?php echo $row->id; ?> <?=checker('select', $row->id, $_POST['item_select'])?>> <?php echo $row->name; ?></option>
        <?php }// end while?>
    </select>

If you're only needing to do this once then this is overkill but you should be able to take the principle and apply it to your code.

Upvotes: 1

matino
matino

Reputation: 17705

Just compare the submited value with the current one in for loop:

<option value="<?php echo $row->id ?>" <?php echo $row->id == $_POST['item_select'] ? 'selected' : '' ?> ><?php echo $row->name ?></option>

Upvotes: 2

Related Questions