views:

377

answers:

7

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?

A: 

It looks like the answer is no:

http://www.w3.org/TR/html401/interact/forms.html#h-17.6.1

Jefe
+4  A: 

Nope, the existence of the selected attribute tells the browser that it is the selected item. Anything inside the quotes is ignored.

Edit: What you could do (with Javascript) is look for option tags with selected="", and remove the selected attribute from them.

jimyi
+1  A: 

According to w3schools, you should be setting it as: selected="selected". This tells you which option is initially selected, and allows you to set it through script later.

amischiefr
A: 

You are better off setting the selectElement.selectedIndex property from Javascript, or removing the attribute altogether.

Jeff Meatball Yang
+1  A: 

Different browser may treat this attribute differently. According to the MSDN documentation (for Internet Explorer):

To select an item in HTML, it is not necessary to set the value of the SELECTED attribute to true. The mere presence of the SELECTED attribute set its value to true.

In firefox and Safari this does work:

<option selected='false' />

From what I can tell by looking at the official WC3 standard for HTML4, the supported case is only:

<option selected='selected' />

You will either need to selectively emit the attribute, or use javascript to control which item is initially selected.

LBushkin
A: 

There aren't any other valid values other than "selected" for that attribute. (http://www.w3schools.com/TAGS/att_option_selected.asp)

Chet
+3  A: 

the only allowed value for selected attribute in XHTML is "selected" so if you want your markup to be XHTML compliant and work across all browsers leaving it out is the only choice to make it unselected

Rony