KarthickN
KarthickN

Reputation: 335

How can I add only unique options in multiple select tags which are in same class?

I need to dynamically add options to the select tags. Those options I will be fetching it from a file. There can be many selects in the form. Now I need to check all the selects whichever is in the same class If it doesn't have the option which I fetched from the file Then I need to add that option to that particular select.

var name = $(this).attr('name');
$('.slct').each(function(){
    if($('this option[value="'+name+'"]').length==0)
    {
        $('<option>').val(name).text(name).appendTo(this);
    }
});

When I tried the above code, Options are getting duplicated. For example I have 3 select tags. In the first tag I have an option called option1 remaining two tags are empty. Then after the execution of this code. First select tag contains the option1 twice and the remaining two tags contain only once. Can Someone tell me how do I do it ? I am new to jquery.

Upvotes: 0

Views: 1001

Answers (1)

Ehsan Sajjad
Ehsan Sajjad

Reputation: 62488

You can use find() to check if option with specific value exists in the select this way:

if($(this).find('option[value="'+name+'"]').length==0)
{
    $('<option>').val(name).text(name).appendTo(this);
}

FIDDLE DEMO:

http://jsfiddle.net/3Lkv638x/1/

Upvotes: 1

Related Questions