Skip to content

Files

Latest commit

 

History

History
84 lines (70 loc) · 2.47 KB

5ee43a1fc66658f802c8b2cb.md

File metadata and controls

84 lines (70 loc) · 2.47 KB
title date submitter number tags discussion
I want to specify the value of a `select` directly (instead of through `option`)
2020-06-13 02:29:51 UTC
Nikunj Bhatt
5ee43a1fc66658f802c8b2cb
html

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>