I know there are multiple ways to select a particular option from a using jQuery:
$select.val("someValue")$option.attr("selected", "selected")$select[0].selectedIndex = 1
Assuming you have both the index of the option you wish to be selected and its value, what’s the most correct way (from the above, or otherwise) to make it selected?
By “most correct”, I mean:
- Best practice, if any
- Will correctly set the value so that it is submitted with the form, and can be retrieved using any of the above methods
- Any other reason why I’d choose one method over others
That’s fine, in the common case where it’s a non-
multipleselect and you don’t have two different<option>s with the samevalue. If that’s the case I’d go with this, as the most readable option.That’s more direct, so marginally quicker, and is necessary to be unambiguous for the case where you have multiple options with the same value.
If you might have a
multiple-select, you have to get/set the selectedness of each option separately:However:
Not generally the best approach. The problem with
attr()is it’s a nasty hack to access DOM properties and HTML attributes as if they are the same thing, trying to hide the difference from you. Whatattr()will do in this case is to set theselectedDOM property, which is a boolean value. Soattr('selected', true)would make more sense;'selected'as a string value does also work, but only because all non-empty string values are ‘truthy’ in JavaScript.If you were actually setting the HTML
selectedattribute here, it would not have an effect on the selectedness of the option, because theselectedattribute actually maps to thedefaultSelectedproperty and notselected! Theselectedproperty reflects the runtime form contents as altered by the user;defaultSelectedreflects the actual attribute in the document containing the initial selectedness state.(Except on IE, due to a bug in its implementation of default values, and also in other browsers in some situations which are too intricate and confusing to go into. Take-home advice: don’t try setting the
selectedHTML attribute from script as the results may be unpredictable. Work with the DOM properties. The same is also true ofvalue/defaultValuefor inputs andchecked/defaultCheckedfor checkbox/radio.)