Ajey
Ajey

Reputation: 8202

Remove duplicate names in HTML select box

How do I remove duplicate names in HTML select box via jQuery. Here is the fiddle - Fiddle Demo

I tried using -

$('select option').each(function() {
  $(this).prevAll('option[value="' + this.value + '"]').remove();
});

but this only removes duplicate entries when the option value are same.

How to I remove duplicates when the text is same but option values are different

Upvotes: 0

Views: 463

Answers (3)

Indranil Mondal
Indranil Mondal

Reputation: 2857

Try this:

$('select option').each(function() {
    $(this).prevAll('option[value="' + this.text + '"]').remove();
});

Upvotes: 0

Ram
Ram

Reputation: 144689

var $o = $('select option');
$o.filter(function(i, el) {
    return $o.filter(function() { 
              return this.textContent === el.textContent; 
           }).index() !== i;
}).remove();

http://jsfiddle.net/msL6yLzd/

Upvotes: 0

ekans
ekans

Reputation: 1714

you can use a array to see if the value is already attribued :

label = new Object();
$('select option').each(function(){
    if(label[$(this).text()] != 1)
        label[$(this).text()] = 1;
    else $(this).remove();
 });

http://jsfiddle.net/b6fxLnv2/3/

Upvotes: 1

Related Questions