简体   繁体   中英

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

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?

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? ).

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM