Gerben Jacobs
Gerben Jacobs

Reputation: 4583

Select item with comma separated data-attribute

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

Answers (2)

Meabed
Meabed

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 )!


The below is the correct implementation:

http://jsfiddle.net/E9qXe/

$(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

Mark Pieszak - Trilon.io
Mark Pieszak - Trilon.io

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:

jsFiddle Demo

Upvotes: 4

Related Questions