Reputation: 157
I have a select picker dropdown. I'm appending option values dynamically from backend but when same values come, there are duplicate options in the drop down. I want to have only unique values in the drop down. How to check if a value already exists before appending it to the drop down?
I'm appending the value something like this:
$("#pid").append('<option value="'+strSplit[0]+'"selected="">'+strSplit[0]+'</option>');
$("#pid").selectpicker("refresh");
Upvotes: 5
Views: 1085
Reputation: 780724
Use a selector to look for an existing option with the same value. If it doesn't exist, add it.
if ($("#pid option[value=" + strSplit[0] + "]").length == 0){
$("#pid").append('<option value="'+strSplit[0]+'"selected="">'+strSplit[0]+'</option>');
$("#pid").selectpicker("refresh");
}
Upvotes: 4