tags:

views:

49

answers:

1

I want the DropDown text to be retained when the Form returns from POST. How to maintain the state?

+3  A: 

You have to set the selected attribute on the option element.
See http://reference.sitepoint.com/html/option/selected

<form>
  <label for="favoritefood">Favorite food</label>
  <select name="favoritefood" id="favoritefood">
    <option value="che">Cheese</option>
    <option value="egg" selected="selected">Egg</option>
    <option value="cab">Cabbage</option>
  </select>
</form>

The $_POST array will either contain the numeric index of the option element or the value if this attribute is specified. In the example above, $_POST['favoritefood'] contains 'egg'. You could build a helper that builds the option elements for you, e.g.

<?php
class HtmlHelper
{
    public static function option($value, $label, $selected)
    {
        $selected = ($value === $selected) ? ' selected="selected"' : '';
        return sprintf('<option value="%s"%s>%s</option>%s',
                       $value, $selected, $label, PHP_EOL);
    }
}
// Usage to get the above Selectbox options
echo HtmlHelper::option('che', 'Cheese', $_POST['favoritefood']),
     HtmlHelper::option('egg', 'Egg', $_POST['favoritefood']),
     HtmlHelper::option('cab', 'Cabbage', $_POST['favoritefood']);

Of course, it would be smarter to have a Selectbox helper instead which you can pass the options and the POST array in one go, instead of calling it for each option separately. I leave it up to you to build this.

If you are not building your Select options dynamically with PHP, you can select the option by adding a small javascript to your page that you pass the value set for favoritefood from the $_POST array and have the script select the option. See the answers to this question for possible code.

Gordon
No it is not working. The DropDown is filled dynamically and I set "selected", but it is not working.
RPK
If it is not working, you are doing something wrong. The selected attribute is the correct and only way to do it.
Gordon
Selected works when I am not dynamically filling.
RPK
Well, what should I make from this? :) Check your sourcecode to see if the selected attributed is applied from your dynamic filling. If there is multiple selected attributes in your options, the SelectBox must have the multiple attribute: http://reference.sitepoint.com/html/select/multiple
Gordon