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.
Remove duplicate values Select the range of cells that has duplicate values you want to remove. Tip: Remove any outlines or subtotals from your data before trying to remove duplicates. Click Data > Remove Duplicates, and then Under Columns, check or uncheck the columns where you want to remove the duplicates.
You also can remove the duplicates from the table list firstly, then create the drop down list. Select the column range you want to use in the table, the press Ctrl + C to copy it, and place it to another position by pressing Ctrl + V. Then keep selecting the list, click Data > Remove Duplicates.
The below codes works fine for two dropdowns, but not for more than 2. var $select = $("select[id$='go']"); $select. change(function() { $select . not(this) .
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(); });
You can do something like this:
var previousOption;
$('select[name=company] option').each(function() {
if (this.text == previousOption) $(this).remove();
previousOption= this.text;
});
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();
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With