Hi,
i want to sort the drop down items using javascript,can anyone tell me how to do this.
From stackoverflow
-
Put the option values and text into an array, sort the array, then replace the existing option elements with new elements constructed from the sorted array.
mrTomahawk : here is a link I found which shows how to do this: http://www.w3schools.com/jsref/jsref_sort.asp -
You could use jQuery and something like this:
$("#id").html($("#id option").sort(function (a, b) { return a.text == b.text ? 0 : a.text < b.text ? -1 : 1 }))
But it's probably better to ask why and what you're trying to accomplish.
Sean Bright : +1 based purely on what it would take to do without jQuery (see answer below).shanabus : This worked great for me. My drop down is populated on change of another drop down. This code did the trick! Thanks @mastro -
<select id="foo" size="10"> <option value="3">three</option> <option value="1">one</option> <option value="0">zero</option> <option value="2">two</option> </select> <script> // WARN: won't handle OPTGROUPs! var sel = document.getElementById('foo'); // convert OPTIONs NodeList to an Array // - keep in mind that we're using the original OPTION objects var ary = (function(nl) { var a = []; for (var i = 0, len = nl.length; i < len; i++) a.push(nl.item(i)); return a; })(sel.options); // sort OPTIONs Array ary.sort(function(a,b){ // sort by "value"? (numeric comparison) // NOTE: please remember what ".value" means for OPTION objects return a.value - b.value; // or by "label"? (lexicographic comparison) //return a.text < b.text ? -1 : a.text > b.text ? 1 : 0; }); // remove all OPTIONs from SELECT (don't worry, the original // OPTION objects are still referenced in "ary") ;-) for (var i = 0, len = ary.length; i < len; i++) sel.remove(ary[i].index); // (re)add re-ordered OPTIONs to SELECT for (var i = 0, len = ary.length; i < len; i++) sel.add(ary[i], null); </script>
bobince : .value comparison will only work for numerics; for lexicographic sorting see the comparator in masto's answer.altblue : Sorry, but I don't understand what's the point of your comment, as I'm sure you have looked ONE line below that numeric comparison that does exactly a, guess what, "lexicographic comparison" on options' "text"?! :(Crescent Fresh : Nice use of -
I have done an example on how you could sort a drop down list using JQuery. You could check it out if you're interested. This example takes all the select elements on the page and sort them alphabetically.
0 comments:
Post a Comment