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?
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.
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 option
s are accessed one by one (by .val()
) - lookup for .sibling()
option
s that have the same "[value='"+ this.value +"']"
and .remove()
them.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With