Arkymedes
Arkymedes

Reputation: 179

How to sort options in select list but keeping one at the top

Right now I have the following code that goes through my list and sort them alphabetically:

<select id="country" class="inputList" name="country">
    <option value="">Select your country</option>
    <option value='0'>Afghanistan</option>
    <option value='1'>Albania</option>
    <option value='2'>Algeria</option>
    <option value='3'>Andorra</option>
    ...
</select>

How to make it so the script EXCLUDES the option that has NO value (the first one "Select your Country)?

$("#country").html($("#country option").sort(function (a, b) {
return a.text == b.text ? 0 : a.text < b.text ? -1 : 1
}))

Thanks a lot!

EDIT: The solution as pointed by Offbeatmammal is here: sort items in a dropdown list without the first item

Upvotes: 1

Views: 6945

Answers (2)

Offbeatmammal
Offbeatmammal

Reputation: 8226

[turning comment into Answer as it solved the problem]

I'd probably cheat... strip off the top one, do the sort and then put it back in ... in fact, this answer - sort items in a dropdown list without the first item - does just that

Upvotes: 2

Dan Pichelman
Dan Pichelman

Reputation: 2332

I usually pull that item out of the list, sort the rest, then reinsert it.

Upvotes: 1

Related Questions