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 alread
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");
}
});
if ( $("#your_select_id option[value=<enter_value_here>]").length == 0 ){
alert("option doesn't exist!");
}
This evaluates to true if it already exists:
$("#yourSelect option[value='yourValue']").length > 0;
var exists = $("#yourSelect option")
.filter(function (i, o) { return o.value === yourValue; })
.length > 0;
This has the advantage of automatically escaping the value for you, which makes random quotes in the text much easier to deal with.
Does not work, you have to do this:
if ( $("#your_select_id option[value='enter_value_here']").length == 0 ){
alert("option doesn't exist!");
}
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);
}