Asked 3 years ago
29 Jun 2021
Views 401
Marielle

Marielle posted

How can I set the default value for an HTML <select> element

How can I set the default value for an HTML <select> element
lain

lain
answered Apr 28 '23 00:00

Here's a possible way to rewrite the answer to avoid duplicate content:

To specify a default value for an HTML <select> element, you can use the selected attribute on one of the <option> elements inside the <select> element.

For instance, suppose you have the following <select> element:



<select name="color">
  <option value="red">Red</option>
  <option value="green">Green</option>
  <option value="blue">Blue</option>
</select>

To set "Green" as the default value, you can add the selected attribute to the corresponding <option> element:



<select name="color">
  <option value="red">Red</option>
  <option value="green" selected>Green</option>
  <option value="blue">Blue</option>
</select>

With this code, the "Green" option will be pre-selected when the page loads. If the user submits the form without changing the selection, "green" will be the value submitted.

To set the default value dynamically with PHP, you can check a submitted value or a default value from a database or another data source, and add the selected attribute to the corresponding <option> element. Here's an example:



<select name="color">
  <option value="red" <?php if ($color == 'red') echo 'selected'; ?>>Red</option>
  <option value="green" <?php if ($color == 'green') echo 'selected'; ?>>Green</option>
  <option value="blue" <?php if ($color == 'blue') echo 'selected'; ?>>Blue</option>
</select>

In this code, $color is a PHP variable holding the value to be pre-selected. If $color is "green" , the "Green" option will have the selected attribute added, pre-selecting it.
Post Answer