Filter duplicate options from select dropdown

前端 未结 3 734
终归单人心
终归单人心 2020-12-15 10:39

I have a dropdown selector generated from a list and want to filter the options to remove the duplicate entries. e.g. I want to filter ...


                        
    
提交评论

  • 2020-12-15 11:13

    You can do it with a simple loop - there may be a cleverer way to handle this with jQuery selectors that I'm not seeing, though. The following should work:

    var usedNames = {};
    $("select[name='company'] > option").each(function () {
        if(usedNames[this.text]) {
            $(this).remove();
        } else {
            usedNames[this.text] = this.value;
        }
    });
    

    Edit: Here's a functional-style one-liner that does it with the help of the excellent Underscore.js, although the previous version is almost certainly more efficient:

    _.each(_.uniq(_.pluck($("select[name='company'] > option").get(), 'text')), function(name) { $("select[name='company'] > option:contains(" + name + ")").not(":first").remove(); });
    
    0 讨论(0)
  • 2020-12-15 11:14

    You can do something like this:

    var previousOption;
    $('select[name=company] option').each(function() {
        if (this.text == previousOption) $(this).remove();
        previousOption= this.text;
    });
    
    0 讨论(0)
  • 提交回复
    热议问题