views:

390

answers:

3

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.

+1  A: 

You can do something like this:

var previousOption;
$('select[name=company] option').each(function() {
    if (this.text == previousOption) $(this).remove();
    previousOption= this.text;
});
Justin Swartsel
Think you're going to want the text() not val() in this case.
Ryan
Three notes: 1. I think you'd want to use text() rather than val(); since the values appear to be different. 2. This wouldn't catch a case where duplicate values alternate (i.e. Microsoft, Apple, Microsoft), although it's not clear from the original question whether that's a possibility. 3. I'd recommend calling $(this) only once at the beginning of the function (i.e. `var option = $(this);`), as I believe it's a moderately expensive operation.
Greg Campbell
Thanks for the good thoughts. val(), however, did return the correct value for me in this case. I agree text would be better.
Justin Swartsel
+3  A: 

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(); });
Greg Campbell
Thanks. This is pretty much what I was looking for, but I was getting tied up with the JS syntax.
afewscoops
A: 

You can try the following code, it will remove the duplicates regardless of their position. Here #targetSelect is your target Dropdown

var a = new Array();
$(#targetSelect).children("option").each(function(x){
test = false;
b = a[x] = $(this).text();
for (i=0;i<a.length-1;i++){
if (b ==a[i]) test =true;
}
if (test) $(this).remove();
}); 
Namwar Rizvi