Nikhil K S
Nikhil K S

Reputation: 804

How to check a option available in drop down using jquery

How to create a ageneric function to add more options to the drop-down Eg:"AddItemToDropdown".

Problem: Before adding a option how to check that field is already available in that dropdown

Now i'm working by removing the field before adding, any idea how to check is exist in dropdown

$(sourceDropdownId+' option[value=' + key + ']').remove();

<select id="Names">
    <option>mike1</option>
    <option>mike2</option>
    <option>mike3</option>
</select>

function AddItemToDropdown(sourceDropdownId, key, text) {
    var exists = 0 != $(sourceDropdownId + ' option[value=' + key + ']').length;
    if (exists) {
        $(sourceDropdownId)
            .append($("<option></option>")
                .attr("value", key)
                .text(text));
    }
}

Upvotes: 1

Views: 1023

Answers (1)

Milind Anantwar
Milind Anantwar

Reputation: 82231

You have errors in your code. You need to create id selector to target select element. also you can check the length as conditional statement. this goes same for logic when you are trying to append new option elements:

function AddItemToDropdown(sourceDropdownId, key, text) {
 if (!$('#'+sourceDropdownId + ' option[value=' + key + ']').length) {
     $('#'+sourceDropdownId).append($("<option></option>").attr("value", key).text(text));
 }
}

Working Demo

Upvotes: 3

Related Questions