Muleskinner Muleskinner - 1 year ago 69
HTML Question

Should I explicit specify default value for SELECT even if it is the first one

In all browsers that I know of, the first option is selected pr default in the below HTML:


But can I count on this behavior? Or would it be better practice to explicit specify default value even when it is the first option, ie would it be safer to go:

<option selected>foo</option>

Answer Source

The HTML(5) specification doesn't say that the default selected option should be the first one if no selected attribute is present.

The selectedness of an option element is a boolean state, initially false. Except where otherwise specified, when the element is created, its selectedness must be set to true if the element has a selected attribute. Whenever an option element's selected attribute is added, its selectedness must be set to true.

It does however say that if no selected value is present then the default should be to return a selectedness value of -1.

The selectedIndex IDL attribute, on getting, must return the index of the first option element in the list of options in tree order that has its selectedness set to true, if any. If there isn't one, then it must return −1.

I guess you therefore shouldn't assume that the first option will always be selected as default.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download