Sort a <select...> by any attribute


<script type="text/javascript"> var sortAttribute,sortAsNum; function SortSelect(sel,attr,isNum){ //sel == object reference to the select to sort //attr == attribute name to sort by ('text' is used if ommitted) //isNum== should a numeric or text compare be used? if (!sel) return; sortAttribute = attr?attr:'text'; sortAsNum = isNum; for (var numOpts=sel.options.length,i=numOpts-1,opts=[];i>=0;i--){ opts[i]=sel.options[i]; sel.options[i]=null; } opts.sort(SortBySortOrder); for (var i=0;i<numOpts;i++) sel.options[i]=opts[i]; } function SortBySortOrder(a,b){ if (!sortAttribute) return 0; var aOrder = a.getAttribute(sortAttribute); var bOrder = b.getAttribute(sortAttribute); if (sortAsNum){ aOrder*=1; bOrder*=1; } return (aOrder<bOrder?-1:aOrder>bOrder?1:0); } </script> <select size="5" multiple id="foo"> <option value="PHL" sortOrder="7">Hoagies - PHL - 7</option> <option value="DIA" sortOrder="1">Mountains - DIA - 1</option> <option value="WDC" sortOrder="70">Crime - WDC - 70</option> <option value="LAX" sortOrder="8">Traffic - LAX - 8</option> <option value="STL" sortOrder="3">Arch - STL - 3</option> </select> <p>sort: <button onclick="SortSelect(document.getElementById('foo'))">by .text</button> <button onclick="SortSelect(document.getElementById('foo'),'value')">by .value</button> <button onclick="SortSelect(document.getElementById('foo'),'sortOrder',true)">by .sortOrder</button> </p>