Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing duplicates from a select dropdown using javascript or jquery

I have a select dropdown field that is being created dynamically from a database based on locations. Due to the way this is being created it results in the dropdown having duplicate locations listed.

<label for="club_feed_town">Location:</label>
<select id="locationList" name="club_feed_town">
    <option value="">All Locations</option>
    <option value="Andover">Andover</option>
    <option value="Andover">Andover</option>
    <option value="Bishops waltham">Bishops waltham</option>
    <option value="Blandford forum">Blandford forum</option>
    <option value="Boscombe">Boscombe</option>
    <option value="Bournemouth">Bournemouth</option>
    <option value="Bournemouth">Bournemouth</option>
    <option value="Etc">Etc</option>
</select>

Does anyone know if there is a way to use some code on the page which checks the dropdown for duplicates and removes any duplicates from the menu?

Thanks in advance,

Tom

like image 208
Tom Perkins Avatar asked Feb 04 '16 17:02

Tom Perkins


People also ask

How can we prevent duplicate values in multiple dropdown using jquery?

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

What is the best way to remove duplicates from a JavaScript array?

Use the filter() method: The filter() method creates a new array of elements that pass the condition we provide. It will include only those elements for which true is returned. We can remove duplicate values from the array by simply adjusting our condition.

Does Set remove duplicates JavaScript?

1) Remove duplicates from an array using a SetThe new Set will implicitly remove duplicate elements. Then, convert the set back to an array.


2 Answers

Simple enough using jQuery and a temporary array to store values ( or text)

Following assumes values are repeated

var optionValues =[];
$('#selectID option').each(function(){
   if($.inArray(this.value, optionValues) >-1){
      $(this).remove()
   }else{
      optionValues.push(this.value);
   }
});

DEMO

like image 56
charlietfl Avatar answered Oct 03 '22 14:10

charlietfl


A modern JS solution without jQuery:

const options = []

document.querySelectorAll('#locationList > option').forEach((option) => {
    if (options.includes(option.value)) option.remove()
    else options.push(option.value)
})
like image 32
tobi Avatar answered Oct 03 '22 16:10

tobi