Add Selected Attribute To Option In Select Menu With JQuery


Answer :

As of jQuery 1.6 "To retrieve and change DOM properties such as the checked, selected, or disabled state of form elements, use the .prop() method."

$("#someselect option[value=somevalue]").prop("selected", "selected") 

Edit:

Select Option:

$("#someselect option[value=somevalue]").prop("selected", true) 

Deselect Option:

$("#someselect option[value=somevalue]").prop("selected", false) 

Check out this previous detailled answer on SO:

If you really want to maitain HTML output with selected attribute, and not only have jQuery maitaining the right selectedIndex attribute on the select element, you can hack with original settAttr() function:

select[0].options[select[0].selectedIndex].setAttribute('selected','selected'); 

But as soon as you keep using jQuery methods for val() or ':selected', you should'nt get any problem, you could have problem only if you were parsing HTML to find selected attribute, something you should'nt do, never.


Comments

Popular posts from this blog

Converting A String To Int In Groovy

"Cannot Create Cache Directory /home//.composer/cache/repo/https---packagist.org/, Or Directory Is Not Writable. Proceeding Without Cache"

Android How Can I Convert A String To A Editable