Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Remove duplicate dropdown option elements with same value

Tags:

jquery

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?

like image 828
Sush Avatar asked May 19 '14 03:05

Sush


People also ask

Which methods is used to remove duplicates?

If the order of the elements is not critical, we can remove duplicates using the Set method and the Numpy unique() function. We can use Pandas functions, OrderedDict, reduce() function, Set + sort() method, and iterative approaches to keep the order of elements.


1 Answers

Using .siblings() (to target sibling option elements), and Attribute Equals Selector [attr=""]

$(".select option").each(function() {
  $(this).siblings('[value="'+ this.value +'"]').remove();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<select class="select">
  <option value="">All</option>
  <option value="com">.com 1</option>
  <option value="net">.net 1</option>
  <option value="com">.com 2</option> <!-- will be removed since value is duplicate -->
  <option value="net">.net 2</option> <!-- will be removed since value is duplicate -->
</select>

(works also for multiple .select on the same page)
I added a class .select to the <select> element to be more selector-specific

How it works:
while options are accessed one by one (by .val()) - lookup for .sibling() options that have the same "[value='"+ this.value +"']" and .remove() them.

like image 88
Roko C. Buljan Avatar answered Oct 23 '22 05:10

Roko C. Buljan