DropDown should save text after POST

I want DropDown text to be saved when the Form returns from POST. How to save a state?

0
source share
1 answer

You must set the attribute selectedin the element option.
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 array $_POSTwill either contain the numerical index of the option element, or valueif this attribute is specified. The above example $_POST['favoritefood']contains an "egg". You can create an assistant that will create option elements for you, for example.

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

, Selectbox, POST , , . , .

PHP, , javascript, , $_POST, script , . .

+4

Source: https://habr.com/ru/post/1796692/