I have jQuery but I'm not sure if it has any built-in sorting helpers. I could make a 2d array of each item's text
, value
, and selected
properties, but I don't think that javascript's built in Array.sort()
would work correctly.
相关问题
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- How to toggle on Order in ReactJS
- PHP Recursively File Folder Scan Sorted by Modific
- How to fix IE ClearType + jQuery opacity problem i
Well, in IE6 it seems to sort on the nested array's [0] item:
I'll see if this works in other browsers...
Edit: it works in Firefox too, woo hoo!
Is there an easier way than this though? is there some method built into javascript or jQuery that sorts selects that I am missing, or is this the best way?
I've just wrapped Mark's idea in a jquery function
JQuery function:
Extract options into a temporary array, sort, then rebuild the list:
Mozilla's sort documentation (specifically the compareFunction) and Wikipedia's Sorting Algorithm page are relevant.
If you want to make the sort case insensitive, replace
text
withtext.toLowerCase()
The sort function shown above illustrates how to sort. Sorting non-english languages accurately can be complex (see the unicode collation algorithm). Using localeCompare in the sort function is a good solution, eg:
Remember: if you want to use context selector, just concatenate the ID will not work
The solution I mentioned in my comment to @Juan Perez
Usage:
This can still be improved on, but I didn't need to add any more bells or whistles :)
Array.sort()
defaults to converting each element to a string, and comparing those values. So["value", "text", "selected"]
gets sorted as"value, text, selected"
. Which will probably work fine, most of the time.If you do want to sort on value alone, or interpret value as a number, then you can pass a comparison function into sort():