Sort html select box but ignore the option that says Select

HI

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 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 &amp; 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;
}));

Give it an ID? That or just target it by name. Go check out how to use a name selector.

One option you can do to solve the problem is sort the options, then simply insert the empty select option in after everything is sorted. Check out https://api.jquery.com/insertBefore/ for more information.

thanks i’ll try the name selector.

Why not sort the data BEFORE the select box is loaded? That’ll be cleaner and easier.

4 Likes