tags:

views:

31

answers:

2

I have a select element that shows multiple options with the same text:

 <select name="tur" id="tur">
        <option value="1">a</option> 
        <option value="2">a</option>  
        <option value="3">a</option> 
        <option value="4">a</option>
        <option value="5">b</option> 
        <option value="6">b</option>  
        <option value="7">c</option> 
         <option value="8">d</option>          
          </select>  

Using JavaScript, I would like to remove these duplicates so that only one of each is shown:

<select name="tur" id="tur">
        <option value="1">a</option> 
        <option value="5">b</option> 
        <option value="7">c</option>
        <option value="8">d</option>          

+2  A: 

You can loop through the <option> elements, checking each one to see if its text content is in an array. If it is, remove the <option>. If not, add its content to the array. This will remove options that are redundant in the list.

Try it out: http://jsfiddle.net/FXq8W/

​var array = [];

​$('#tur option').each(function() {
    var $th = $(this);
    var text = $th.text();
    if( $.inArray(text, array) > -1 ) {
        $th.remove();
    } else {
        array.push( text );
    }
});​​​​​​​​​​​​​​
patrick dw
A: 
var remove = [], values = {}, value, i;
var options = document.getElementById('tur').getElementsByTagName('option');
for (i=0; i<options.length; i++) {
  value = options[i].innerHTML.replace(/^\s*|\s*$/g, '');
  if (value in values) remove.push(options[i]);
  else values[value] = true;
}

for (i=0; i<remove.length; i++) {
  remove[i].parentNode.removeChild(remove[i]);
}
MooGoo