Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mark selected options in for the option HTML tag?

I am using normal select and mutliselect boxes on my site. should I use <option selected="selected"> or simply <option selected> for selected items ?

like image 215
peter Avatar asked Jun 04 '12 12:06

peter


People also ask

How do you make an option tag selected in HTML?

The selected attribute is a boolean attribute. When present, it specifies that an option should be pre-selected when the page loads. The pre-selected option will be displayed first in the drop-down list. Tip: The selected attribute can also be set after the page loads, with a JavaScript.

How do you find all selected options of HTML select tag?

find(“option:selected”) or simply $(“option:selected”). In both the methods “option:selected” is a must which gives us the first selected option. Note: It is suggested to use $(“select”) . find(“option:selected”) because using this you can select options from a specific select tag if multiple select tags are there.

How do you show options in HTML?

The <option> tag defines an option in a select list. <option> elements go inside a <select>, <optgroup>, or <datalist> element. Note: The <option> tag can be used without any attributes, but you usually need the value attribute, which indicates what is sent to the server on form submission.


1 Answers

HTML5 spec:

https://www.w3.org/TR/html5/forms.html#attr-option-selected

The selected 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 XHTML (but valid HTML) and other alternatives are less readable. Else, just use <option selected> as it is shorter.