Sush Sush - 6 months ago 129
jQuery Question

How to Remove duplicate dropdown option elements with same value

How can I remove duplicate values -> drop down option elements?

I have the following HTML:

<option value="">All Servers</option>
<option value="com">http://smiles.com</option>
<option value="in">http://3smiles.com</option>
<option value="com">http://desk.com</option>
<option value="in">http://france24.com</option>


from the above I have to remove repeated values
com
and
in
, so my expected output should be like:

<option value="">All Servers</option>
<option value="com">http://smiles.com</option>
<option value="in">http://3smiles.com</option>


How to do it using jQuery?

Answer

http://jsbin.com/Remove-Options-With-Same-Value

$(".select option").each(function(){
  $(this).siblings("[value='"+ this.value+"']").remove();
});

which works also for multiple .select on the same page: demo
I added a class .select to your <select> element to be more selector-specific

Another nice way:

$(".select option").val(function(i,v){
  $(this).siblings("[value='"+ v +"']").remove();
});


What the above examples do is basically:
once the first option is accessed, remove every .siblings() options that share the same "[value='"+ this.value +"']" using the jQuery's Attribute Equals Selector

Comments