Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to have only unique options in select picker drop down?

Tags:

html

jquery

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");
like image 833
coder8888 Avatar asked Jul 05 '17 03:07

coder8888


1 Answers

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");
}
like image 81
Barmar Avatar answered Nov 05 '22 02:11

Barmar