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
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) .
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.
1) Remove duplicates from an array using a SetThe new Set will implicitly remove duplicate elements. Then, convert the set back to an array.
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
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)
})
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