Reputation: 4583
Considering the following:
<option value="de" data-countries="at,ch,li">German</option>
How can I make a jQuery selector that sets this option as the selected one? (With ccl
being the lowercase country code)
if ($("#select option[value='"+ccl+"']").length > 0) {
select.val(ccl); // Pick this one
} else {
$("#select:contains("+ccl+")").attr('selected', 'selected'); // Pick one from the country list
}
This one doesn't really work, because the :contains
doesn't know where to search really.
Edit: I have full control over the source code, so if the comma separated list isn't ideal, I can change things.
Upvotes: 3
Views: 5035
Reputation: 3938
The previous answer will get you wrong select if two words has same letters in different options for Example
<option value="us" data-countries="atx,chy">US</option>
<option value="de" data-countries="at,ch,li">German</option>
In the above example if you used the previous answer it will with value "at" it will select the first option also ( which is wrong )!
$(function () {
ccl = 'tx';
$('#select option').each(function(){
countries = $(this).attr('data-countries');
val = $(this).attr('value');
var countriesArr = countries.split(",");
if(jQuery.inArray(ccl,countriesArr) > -1){
$('#select').val(val);
}
});
});
Upvotes: 8
Reputation: 67161
You need to look by the data-attribute itself, and use the *=
wildcard (which searches for it anywhere) within it.
$('#select option[data-countries*="' + ccl + '"]')
Example shown here:
Upvotes: 4