is there a quick way to sort the items of a select element? Or I have to resort to writing javascript?
Please any ideas.
<select size="4" name="lstALL" multiple="multiple" id="lstALL" tabindex="12" style="font-size:XX-Small;height:95%;width:100%;"> <option value="0"> XXX</option> <option value="1203">ABC</option> <option value="1013">MMM</option> </select>
The HTML option label attribute specifies the text value that defines the option's shorted label. In the drop-down list, the shorter version will be shown. An object stored in a <select>, <optgroup>, or <datalist> element is defined by the HTML <option> element.
The selection sort algorithm sorts an array by repeatedly finding the minimum element (considering ascending order) from the unsorted part and putting it at the beginning. The algorithm maintains two subarrays in a given array. The subarray which already sorted. The remaining subarray was unsorted.
This will do the trick. Just pass it your select element a la: document.getElementById('lstALL')
when you need your list sorted.
function sortSelect(selElem) { var tmpAry = new Array(); for (var i=0;i<selElem.options.length;i++) { tmpAry[i] = new Array(); tmpAry[i][0] = selElem.options[i].text; tmpAry[i][1] = selElem.options[i].value; } tmpAry.sort(); while (selElem.options.length > 0) { selElem.options[0] = null; } for (var i=0;i<tmpAry.length;i++) { var op = new Option(tmpAry[i][0], tmpAry[i][1]); selElem.options[i] = op; } return; }
This solution worked very nicely for me using jquery, thought I'd cross reference it here as I found this page before the other one. Someone else might do the same.
$("#id").html($("#id option").sort(function (a, b) { return a.text == b.text ? 0 : a.text < b.text ? -1 : 1 }))
from Sorting dropdown list using Javascript
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With