Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 610
Travis Beale Avatar asked Jun 23 '09 17:06

Travis Beale


People also ask

What are the two attributes of option tag?

selected: This attribute contains the value selected which represents the item that is pre-selected when the browser loaded. value: This attribute contains the value text sent to the server.

Does option tag have value attribute?

The value attribute for <option> tag in HTML is used to specify the value of the option element. Attribute Value: It contains single value value which has to be sent to the server. Example: This example illustrates the value attribute in option tag.


1 Answers

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.