Home  >  Article  >  Backend Development  >  How to Set a Default Selection in a Dynamically Generated Drop-Down Box?

How to Set a Default Selection in a Dynamically Generated Drop-Down Box?

Barbara Streisand
Barbara StreisandOriginal
2024-10-21 22:54:02812browse

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 tag is dynamically generated using PHP, and you want to select an option based on the value stored in the database. Here's how you can achieve this:

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn