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?
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.
The correct solution will be is to not to allow the server to have duplicate values....
try
var map = {};
$('select option').each(function () {
if (map[this.value]) {
$(this).remove()
}
map[this.value] = true;
})
Demo: Fiddle