Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
804 views
in Technique[技术] by (71.8m points)

jquery - Filter duplicate options from select dropdown

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 ...

<select name="company">
    <option "1">Microsoft</option>
    <option "2">Microsoft</option>
    <option "3">Microsoft</option>
    <option "4">Microsoft</option>
    <option "5">Apple</option>
    <option "6">Apple</option>
    <option "7">Google</option>
</select>

... down to present the user with something like...

<select name="company">
    <option "1">Microsoft</option>
    <option "5">Apple</option>
    <option "7">Google</option>
</select>

(The data comes from a Sharepoint Lookup on another list and I'm thinking I can use jquery to keep only the unique options without having to go into the guts of what's going on.) Can I remove options like this? Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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(); });

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...