If you know the Index, Value or Text. also if you don\'t have an ID for a direct reference.
This, this and this are all helpful answers.
Example markup
There are a few suggestions why you should use prop
instead of attr.
Definitely use prop
as I've tested both and attr
will give you weird results except for the simplest of cases.
I wanted a solution where selecting from an arbitrarily grouped select
options automatically selected another select
input on that same page. So for instance, if you have 2 dropdowns - one for countries, and the other for continents. In this scenario, selecting any country automatically selected that country's continent on the other continent dropdown.
$("#country").on("change", function() {
//get continent
var originLocationRegion = $(this).find(":selected").data("origin-region");
//select continent correctly with prop
$('#continent option[value="' + originLocationRegion + '"]').prop('selected', true);
});
$("#country2").on("change", function() {
//get continent
var originLocationRegion = $(this).find(":selected").data("origin-region");
//select continent wrongly with attr
$('#continent2 option[value="' + originLocationRegion + '"]').attr('selected', true);
});
As seen in the code snippet, prop
works correctly every time, but attr
fails to select properly once the option has been selected once.
Keypoint: We're usually interested in the property of the attribute, so its safer to use prop
over attr
in most situations.