Home > Enterprise >  Why is it that when I resize my select the first element becomes selected?
Why is it that when I resize my select the first element becomes selected?

Time:12-25

If the size of a <select> tag is dynamically changed from JavaScript, the first element becomes automatically selected if the initial size attribute was either 0 or 1 (MSEdge, Win10).

<select id="s" size="1">
  <option>a
  <option>b
  <option>c
</select>

<select size="3">
  <option>a
  <option>b
  <option>c
</select>

<script>
s.size=3;
</script>

I imagine a size of 0 or 1 forces a selection, but I can't see why this is, as I didn't ask it to.

Does anyone have an explanation?

CodePudding user response:

This is actually covered in the specification:

If nodes are inserted or nodes are removed causing the list of options to gain or lose one or more option elements, or if an option element in the list of options asks for a reset, then, if the select element's multiple attribute is absent, the user agent must run the first applicable set of steps from the following list:

  • If the select element's display size is 1, and no option elements in the select element's list of options have their selectedness set to true
    • Set the selectedness of the first option element in the list of options in tree order that is not disabled, if any, to true.
  • If two or more option elements in the select element's list of options have their selectedness set to true
    • Set the selectedness of all but the last option element with its selectedness set to true in the list of options in tree order to false.
  • Related