Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Cannot set "selected"="selected" via attr() on <option> elements?

<select>
    <option>1</option>
    <option>2</option>
    <option class="test">3</option>
</select>

$('.test').attr('selected', 'selected');​

The select box above would choose the third option as default without any issues. However, if you check the elements with Firebug there isn't any selected="selected" attribute present within the chosen <option>.

I know this isn't a big issue as it still works but I need selected="selected" there so my other scripts could catch it and perform further processing. Are there any workarounds out there?

Thanks.

like image 551
user435216 Avatar asked Sep 16 '10 18:09

user435216


3 Answers

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.

like image 81
bobince Avatar answered Oct 21 '22 23:10

bobince


This works as expected, Check it out : http://jsfiddle.net/MZYN7/1/

like image 29
letronje Avatar answered Oct 21 '22 21:10

letronje


It should be $('.test').attr('selected', true);​

also

<option selected>value</option>

It will not show up as selected="selected"

like image 42
Jakub Avatar answered Oct 21 '22 21:10

Jakub