Home > database >  In a HTML select element, why the last option that has selected=false is selected?
In a HTML select element, why the last option that has selected=false is selected?

Time:06-07

I have a select element with option elements in it. Some of the options have attribute selected set to false, and some don't have it set at all.

<select>
  <option selected=false>1</option>
  <option selected=false>2</option>
  <option>3</option>
  <option selected=false>4</option>
  <option>5</option>
  <option>6</option>
</select>

It seems that when no elements have selected set to true, the last element with selected set to false is the one selected by default when the element is created.

This behavior is not intuitive, and in this case I would expected the first option with undefined selected to be selected, and definitely not one that is explicitly unselected.

What causes this behavior? Is it defined anywhere?

CodePudding user response:

The problem is that disabled is a boolean attribute. When it is present, it is on, and it doesn't matter what value it has, so the last element that has the selected attribute gets selected. Even though you write false, it is still interpreted as true (see What values can appear in the "selected" attribute of the "option" tag?).

CodePudding user response:

Why are using selected False can you please explain the purpose. Try it.

<select>
  <option disabled>1</option>
  <option disabled>2</option>
  <option>3</option>
  <option disabled>4</option>
  <option>5</option>
  <option>6</option>
</select>
  • Related