How can I check whether a option already exist in select by JQuery?
I want to dynamically add options into select and so I need to check whether the option is already exist to prevent duplication.
How can I check whether a option already exist in select by JQuery?
I want to dynamically add options into select and so I need to check whether the option is already exist to prevent duplication.
This evaluates to true if it already exists:
$("#yourSelect option[value='yourValue']").length > 0;
Another way using jQuery:
var exists = false;
$('#yourSelect option').each(function(){
if (this.value == yourValue) {
exists = true;
}
});
if ( $("#your_select_id option[value=<enter_value_here>]").length == 0 ){
alert("option doesn't exist!");
}
Although most of other answers worked for me I used .find():
if ($("#yourSelect").find('option[value="value"]').length === 0){
...
}
It's help me :
var key = 'Hallo';
if ( $("#chosen_b option[value='"+key+"']").length == 0 ){
alert("option not exist!");
$('#chosen_b').append("<option value='"+key+"'>"+key+"</option>");
$('#chosen_b').val(key);
$('#chosen_b').trigger("chosen:updated");
}
});
I had a similar issue. Rather than run the search through the dom every time though the loop for the select control I saved the jquery select element in a variable and did this:
function isValueInSelect($select, data_value){
return $($select).children('option').map(function(index, opt){
return opt.value;
}).get().includes(data_value);
}