I’m trying to understand sorting option elements within a select element alphabetically. Ideally, I’d like to have this as a separate function where I can just pass in the select element since it needs to be sorted when the user clicks some buttons.
I’ve searched high and low for a good way of doing this, but haven’t been able to find anything that worked for me.
The option elements should be sorted alphabetically by text, not value.
Is this possible in some way?
What I’d do is:
<option>into an array of objects;<option>elements with the array contents in order.To do that with jQuery, you could do this:
Here is a working jsfiddle.
edit — If you want to sort such that you ignore alphabetic case, you can use the JavaScript
.toUpperCase()or.toLowerCase()functions before comparing: