How can I check whether a option already exist in select by JQuery
Solution 1:
This evaluates to true if it already exists:
$("#yourSelect option[value='yourValue']").length > 0;
Solution 2:
Another way using jQuery:
var exists = false;
$('#yourSelect option').each(function(){
if (this.value == yourValue) {
exists = true;
}
});
Solution 3:
if ( $("#your_select_id option[value=<enter_value_here>]").length == 0 ){
alert("option doesn't exist!");
}
Solution 4:
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.