I want to specify the value of a select
directly (instead of through option
)
Submitted by Nikunj Bhatt
Permalink https://webwewant.fyi/wants/5ee43a1fc66658f802c8b2cb/
Consider this HTML code:
<select id="s">
<option>opt 1</option>
<option>opt 2</option>
</select>
Browsers are supporting assigning value to the select
element directly through the value
attribute in JavaScript. For example, to set the value "opt 2" selected in the select
element, we can write as following in JS:
document.getElementById('s').value = 'opt 2';
This code will select the 2nd option. However, presently the value
attribute can not be set directly through HTML as following:
<select value="opt 2">
<option>opt 1</option>
<option>opt 2</option>
</select>
This is particularly useful on server side. There, a developer has to implement a loop to match all the option
elements and append the selected
attribute to the selected option
element. For example, in PHP, if $day has value "Friday" and developer wants to specify an option
as selected
which has "Friday" as its value, then they need to do this:
<select>
<?php $day = 'Friday';
$days = [ 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday' ];
for($i = 0; $i < 7; $i++) { ?>
<option <?= ($days[$i] == $day ? 'selected' : '')?>><?= $days[$i] ?></option>
<?php } ?>
</select>
The above code will output as following (selected
attribute in "Friday" option
):
<select>
<option>Sunday</option>
<option>Monday</option>
<option>Tuesday</option>
<option>Wednesday</option>
<option>Thursday</option>
<option selected>Friday</option>
<option>Saturday</option>
</select>
But it should be possible as following too:
<?php $day = 'Friday'; ?>
<select value="<?= $day ?>">
<?php $days = [ 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday' ];
for($i = 0; $i < 7; $i++) { ?>
<option><?= $days[$i] ?></option>
<?php } ?>
</select>
The above code will output as following, and the option
having value "Friday" should be selected by default:
<select value="Friday">
<option>Sunday</option>
<option>Monday</option>
<option>Tuesday</option>
<option>Wednesday</option>
<option>Thursday</option>
<option>Friday</option>
<option>Saturday</option>
</select>