Retaining drop down list box value of a form after posting

Retain a selected option safely

Use an allow-list for accepted option values. The same validated value can then be used to mark the matching option as selected.

$allowed = ['one', 'two', 'three'];
$selected = $_POST['class'] ?? '';

if (!in_array($selected, $allowed, true)) {
    $selected = '';
}

echo '<option value="two"' . ($selected === 'two' ? ' selected' : '') . '>Two</option>';


From a drop down?> From a drop down list box or combo box visitor selects one option and submits the form. If the form validation fails then we have to show again the same form asking for changes in input data and submit again. In this process we have to keep our drop down box selected to the option previously selected by the user. For example in a travel information form, visitor select the week day of travel from a drop down list box having all days of the week and submits the form, then due to any reason the form validation fails and we ask the visitor to again fill the form, we must keep the previously selected day of the week of the visitor as selected only. So if the visitor has selected Monday then the form has to show day Monday as selected day of the week.

There are different ways to do this and one method where the data (or the option) are populated from table is already discussed in double drop down list box tutorial. There all options are matched with an if condition and accordingly the selected attribute is added. Note that there are many ways to achieve this and we will try to explore one way here.

A compact approach is to validate the submitted option against an allow-list and then add the selected attribute while rendering the options. This keeps the sticky form on one page and avoids putting the selected value into a query string.

Here is the same-page POST version. The day is validated against an allow-list before it is used to restore the selected option.

Related: HTML forms and jQuery listbox.

$days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
$t1 = $_POST['t1'] ?? 'Mon';

if (!in_array($t1, $days, true)) {
    $t1 = 'Mon';
}

foreach ($days as $day) {
    $selected = $t1 === $day ? ' selected' : '';
    echo "<option value='$day'$selected>$day</option>";
}
Creating a drop down list box using data from MySQL table
Multiple Selection drop box using PHP
Sitemap Form Form post back data
Checking Data Radio buttons
PHP sticky form using listbox


Subscribe to our YouTube Channel here



plus2net.com







smo1234

18-06-2012

thanks this is working fine
Jnanendra Veer

05-09-2012

thanks this is working fine
Murugavel

04-08-2014

Working perfectly Dude.Thanks




PHP video Tutorials
✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer