How to Remove duplicate dropdown option elements with same value
Using .siblings()
(to target sibling option
elements), and Attribute Equals Selector [attr=""]
$(".select option").val(function(idx, val) {
$(this).siblings('[value="'+ val +'"]').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
use this :
$(document).ready(function () {
var usedNames = {};
$("select > option").each(function () {
if (usedNames[this.value]) {
$(this).remove();
} else {
usedNames[this.value] = this.text;
}
});
});
demo here : http://jsfiddle.net/aelor/aspMT/