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?
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With