Delete duplicate entries from a select box

前端 未结 4 1498
梦谈多话
梦谈多话 2021-01-05 17:18

How would I, using jQuery, remove the dups

        
        
相关标签:
4条回答
  • 2021-01-05 17:43

    The easiest way that came into my mind was using siblings

    $("select>option").each( function(){
    
     var $option = $(this);  
    
     $option.siblings()
           .filter( function(){ return $(this).val() == $option.val() } )
           .remove()
    
    
    })
    
    0 讨论(0)
  • 2021-01-05 17:55

    Try use below code to remove duplicate options:

    $("#color 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-form" name="color" id="color">
      <option value="">Select Color</option>
      <option value="1">Color 1</option>
      <option value="2">Color 2</option>
      <option value="3">Color 3</option>
      <option value="3">Color 3</option> <!-- will be removed since value is duplicate -->
      <option value="2">Color 2</option> <!-- will be removed since value is duplicate -->
    </select>

    0 讨论(0)
  • 2021-01-05 17:56

    You can do it like this:

    var found = [];
    $("select option").each(function() {
      if($.inArray(this.value, found) != -1) $(this).remove();
      found.push(this.value);
    });
    

    Give it a try here, it's a simple approach, we're just keeping an array of found values, if we haven't found the value, add it to the array (.push()), if we have found the value, this one's a dupe we found earlier, .remove() it.

    This only crawls the <select> once, minimizing DOM traversal which is a lot more expensive than array operations. Also we're using $.inArray() instead of .indexOf() so this works properly in IE.


    If you want a less efficient but shorter solution (just for illustration, use the first method!):

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

    You can test it here, this removes all siblings with the same value, but it's much more expensive than the first method (DOM Traversal is expensive, and multiple selector engine calls here, many more). We're using .prevAll() because you can't just remove .siblings() inside an .each(), it'll cause some errors with the loop since it expected the next child. ​

    0 讨论(0)
  • 2021-01-05 17:57

    From top of my head, untested:

    $('#mySelect option').each(function(){
      if ($('#mySelect option[value="'+$(this).val()+'"]').length) $(this).remove();
    });
    
    0 讨论(0)
提交回复
热议问题