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

Barbara Streisand
Release: 2024-10-21 22:54:02
Original
811 people have browsed it

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>
Copy after login

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>
Copy after login

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!

source:php
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!