The selected
attribute does not correspond to the current selectedness state of the option. The selected
attribute corresponds to the default selectedness, which will be restored if .reset()
is called (or a type="reset"
button is clicked) on the form. The current selectedness state can be accessed using the DOM property selected
, whereas the default-selectedness, as reflected by the attribute, is accessed under the DOM property defaultSelected
.
The same goes for value
vs defaultValue
on <input type="text">
/<textarea>
, and checked
/defaultChecked
on type="checkbox"
/"radio"
.
jQuery's attr()
is misleadingly named, and its attempts to pretend attributes and properties are the same thing is flawed. When you use attr()
, you are usually accessing the property, not the attribute. Consequently, $(el).attr('selected', 'selected')
is actually doing el.selected= 'selected'
. This works because 'selected'
, as with any non-empty string, is ‘truthy’: it gets converted to el.selected= true
. But this does not at any point touch the selected="selected"
attribute.
IE further complicates this already confusing situation by (a) getting getAttribute
/setAttribute
wrong so it accesses the properties instead of the attributes (which is why you should never use these methods in an HTML document), and (b) incorrectly mapping the current form state to the HTML attributes, so the attributes do actually appear in that browser.
but I need selected="selected" there
Why? Are you serialising the form to innerHTML
? This won't include form field values (again, except in IE due to the bug), so is not a usable way to store field values.