How can I remove duplicate values -> drop down option elements?
I have the following HTML:
You can use the following code to remove options with duplicate values.
$(document).ready( function(){
var a = new Array();
$("#selectID").children("option").each(function(x){
test = false;
b = a[x] = $(this).val();
for (i=0;i<a.length-1;i++){
if (b ==a[i]) test =true;
}
if (test) $(this).remove();
})
});
How about this.
DEMO :http://jsfiddle.net/naokiota/yayTm/2/
var exist = {};
$('select > option').each(function() {
if (exist[$(this).val()]){
$(this).remove();
}else{
exist[$(this).val()] = true;
}
});
Hope this helps.
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
HTML
<select class="something">
<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>
</select>
jQuery
var seen = {};
jQuery('.something').children().each(function() {
var txt = jQuery(this).attr('value');
if (seen[txt]) {
jQuery(this).remove();
} else {
seen[txt] = true;
}
});
Demo
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.
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/