What values can appear in the "selected" attribute of the "option" tag?

Travis Beale picture Travis Beale · Jun 23, 2009 · Viewed 64k times · Source

I have some markup similar to the following:

<select>
  <option selected="selected">Apple</option>
  <option selected="">Orange</option>
</select>

In this case, "Orange" shows as the selected item. I would have expected making the selected attribute blank would undo its effects. Is there a way to write this without simply leaving the attribute out?

Answer

HTML5 spec

https://www.w3.org/TR/html51/sec-forms.html#the-option-element

The selected content attribute is a boolean attribute.

http://www.w3.org/TR/html5/infrastructure.html#boolean-attributes :

The presence of a boolean attribute on an element represents the true value, and the absence of the attribute represents the false value.

If the attribute is present, its value must either be the empty string or a value that is an ASCII case-insensitive match for the attribute's canonical name, with no leading or trailing whitespace.

Conclusion

The following are valid, equivalent and true:

<option selected />
<option selected="" />
<option selected="selected" />
<option selected="SeLeCtEd" />

The following are invalid:

<option selected="0" />
<option selected="1" />
<option selected="false" />
<option selected="true" />

The absence of the attribute is the only valid syntax for false:

<option />

Recommendation

If you care about writing valid XHTML, use selected="selected", since <option selected> is invalid and other alternatives are less readable. Else, just use <option selected> as it is shorter.