Home > Article > Backend Development > How to Set a Default Selection in a Dynamically Generated Drop-Down Box?
Determining the Selected Item in a Drop-Down Box
When using a
In the scenario you presented, the
Setting the selected Attribute
To set the selected item in a drop-down box, you need to use the selected attribute. This attribute can be applied to the
PHP Solution
In your example, you can use PHP to dynamically set the selected attribute based on the value stored in the $row array:
<option value="January" <?php echo ($row['month'] == 'January' ? 'selected="selected"' : ''); ?>>January</option>
This code checks if the value of $row['month'] is equal to 'January'. If it is, the selected="selected" attribute is applied to the
Array-Based Solution
An alternative and more organized approach is to use an array of values for the drop-down options:
<?php $months = array('January', 'February', 'March', 'April'); ?> <select> <?php foreach ($months as $month) { echo '<option value="' . $month . '" ' . ($row['month'] == $month ? 'selected="selected"' : '') . '>' . $month . '</option>'; } ?> </select>
This solution creates an array of month names and iterates through it to generate the drop-down options. It conditionally sets the selected attribute based on the database value.
The above is the detailed content of How to Set a Default Selection in a Dynamically Generated Drop-Down Box?. For more information, please follow other related articles on the PHP Chinese website!