Recently I had to sort "select" element in my HTML page. I found that this is not so simple task, since it has no build in functionality to sort elements. The solution by using JavaScript is pretty simple, if option value and option text are the same. Just put all the options into Array object and use build-in sort() function
Next step is just fill it back
for(i=0; i<slct.length; i++) {
slct.options[i].text = slctArr[i];
slct.options[i].value = slctArr[i];
}
However more work need to be done in order to sort element where option value is not the same as option text
First of all we need to store text values in the array and also values into array
var slct = document.getElementById('slctElem');
txtArr = new Array();
valArr = new Array();
We also will make a backup of original order of the text element
orgArr = new Array();
Extract all the relevant values and put them into arrays
for(i=0; i<slct.length; i++)
{
txtArr[i] = slct.options[i].text;
valArr[i] = slct.options[i].value;
orgArr[i] = slct.options[i].text;
}
Sort text array
txtArr.sort();
//Now we need to make a loop to fill back the select element
for(i=0; i<slct.length; i++)
{
// make another loop to find coresponding value. Since we have a backup array, the correct value located in the same place(index) as original text
slct.options[i].text = txtArr[i];
for(j=0; j<slct.length; j++)
if (txtArr[i] == orgArr[j])
slct.options[i].value = valArr[j];
}
I am attaching the full working HTML file with example
No comments:
Post a Comment