I've got a dyamically created html select box that i need to sort alphabetically but ignore the placeholder/option that says Select...
I've tired the following from here but realised the select box doens't have an ID only a Name
any ideas?
<select style="width:250px" name="sortbyco">
<option value="">Select2</option>
<!--I would like to keep this at the top-->
<option value="40934">Africa (CAF)</option>
<option value="44624">Asia (AFC)</option>
<option value="29521">Europe (UEFA)</option>
<option value="43099">North & Central America (CONCACAF)</option>
<option value="38731">South America (CONMEBOL)</option>
<option value="46617">Oceania (OFC)</option>
<option value="40934">Africa (CAF2)</option>
</select>
$("#sortbyco").append($("#sortbyco option:gt(0)").sort(function (a, b) {
return a.text == b.text ? 0 : a.text < b.text ? -1 : 1;
}));
CodePudding user response:
Here's a snippet without JQuery. The selector now has an id for easier use in a css selector. A copy of the options array without the empty option is sorted, and re-added to the selector.
const selector = document.querySelector(`#sortbyco`);
// create an array of all options except the empty one
const opts = [...selector.querySelectorAll(`option:not([value='']`)];
// copy to a sorted array (note: use localeCompare to compare strings)
const sortedOpts = opts.sort( (a, b) =>
a.textContent.localeCompare(b.textContent) );
// remove the old options from the selector
opts.forEach(opt => opt.remove());
// add the sorted options to the selector
sortedOpts.forEach( (opt, i) => selector.appendChild(opt) );
<select style="width:250px" id="sortbyco">
<option value="46617">Oceania (OFC)</option>
<option value="43099">North & Central America (CONCACAF)</option>
<option value="40934">Africa (CAF)</option>
<option value="44624">Asia (AFC)</option>
<option value="29521">Europe (UEFA)</option>
<option value="40934">Africa (CAF2)</option>
<option value="38731">South America (CONMEBOL)</option>
<option value="" selected>Select</option>
<!-- ▲ will be at the top after sorting -->
</select>
CodePudding user response:
Here is a jQuery example.
$(function() {
var opts = $("#sortbyco > option:not([value=''])").detach();
opts.sort(function(a, b) {
return $(a).text() == $(b).text() ? 0 : $(a).text() < $(b).text() ? -1 : 1;
});
$("#sortbyco").append(opts);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select style="width:250px" name="sortbyco" id="sortbyco">
<option value="">Select2</option>
<!--I would like to keep this at the top-->
<option value="40934">Africa (CAF)</option>
<option value="44624">Asia (AFC)</option>
<option value="29521">Europe (UEFA)</option>
<option value="43099">North & Central America (CONCACAF)</option>
<option value="38731">South America (CONMEBOL)</option>
<option value="46617">Oceania (OFC)</option>
<option value="40934">Africa (CAF2)</option>
</select>
This uses .sort()
on the Array of jQuery Objects.