Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript to sort contents of select element

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> 
like image 414
Julius A Avatar asked Nov 10 '08 15:11

Julius A


People also ask

How do I sort selected options in HTML?

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.

What is selection sort in JavaScript?

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.


2 Answers

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; } 
like image 149
Matty Avatar answered Oct 13 '22 00:10

Matty


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

like image 30
Terre Porter Avatar answered Oct 12 '22 23:10

Terre Porter