Home >Database >Mysql Tutorial >How to Preselect an Item in a HTML Drop-Down Box?
In web development, the
Consider the following scenario: you have a database that stores a month value, and you want to create an edit page that allows users to modify this month. You'll need a drop-down box prepopulated with the current month from the database.
Solution:
To set the selected item in the drop-down, assign the 'selected' attribute to the appropriate
<option value="January" selected="selected">January</option>
PHP Implementation:
To dynamically set the selected item based on the database value, use the following PHP code:
<option value="January" <?=$row['month'] == 'January' ? ' selected="selected"' : '';?>>January</option>
This code checks if the current month in the database is 'January' and adds the 'selected="selected"' attribute accordingly.
Alternate Approach:
An alternative approach is to create an array of values and iterate over it to generate the drop-down options. This can result in a cleaner and more maintainable code:
<?php $months = ['January', 'February', 'March', 'April', 'May', 'June']; echo '<select>'; foreach ($months as $month) { $selected = $month == $row['month'] ? ' selected="selected"' : ''; echo "<option value='$month'$selected>$month</option>"; } echo '</select>'; ?>
By using this method, you can easily add or remove months from the drop-down without modifying the PHP code.
The above is the detailed content of How to Preselect an Item in a HTML Drop-Down Box?. For more information, please follow other related articles on the PHP Chinese website!