Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to show <Select > in sorted order

How can I sort the <option> elements of a <select> tag using JavaScript?

Here is the HTML I have:

<form action="example.asp">
<div>
<select size="3">
<option value="op2" >Option 2</option>
<option value="op1">Option 1</option>
<option value="op4">Option 4</option>
<option value="op3">Option 3</option>

</select>
</div>
</form> 
like image 827
Tree Avatar asked Dec 03 '22 04:12

Tree


2 Answers

If the value is different than the text, use the following function to sort both of them. This is just an updated version of above solution and will keep both the name and associated value.

<script language="JavaScript" type="text/javascript">
function sortList() 
{ 
    var lb = document.getElementById('mylist'); 
    arrTexts = new Array(); 
    arrValues = new Array(); 
    arrOldTexts = new Array(); 

    for(i=0; i<lb.length; i++) 
    { 
        arrTexts[i] = lb.options[i].text; 
        arrValues[i] = lb.options[i].value; 
        arrOldTexts[i] = lb.options[i].text; 
    } 

    arrTexts.sort(); 

    for(i=0; i<lb.length; i++) 
    { 
        lb.options[i].text = arrTexts[i]; 
        for(j=0; j<lb.length; j++) 
        { 
            if (arrTexts[i] == arrOldTexts[j]) 
            { 
                lb.options[i].value = arrValues[j]; 
                j = lb.length; 
            } 
        } 
    } 
}
</script>
like image 129
Yasir Al-Agl Avatar answered Dec 07 '22 22:12

Yasir Al-Agl


<script language="JavaScript" type="text/javascript">
function sortlist() {
var lb = document.getElementById('mylist');
arrTexts = new Array();

for(i=0; i<lb.length; i++)  {
  arrTexts[i] = lb.options[i].text;
}

arrTexts.sort();

for(i=0; i<lb.length; i++)  {
  lb.options[i].text = arrTexts[i];
  lb.options[i].value = arrTexts[i];
}
}
</script>


<form action="#">
<select name=mylist id=mylist size=5>
<option value="Anton">Anton
<option value="Mike">Mike
<option value="Peter">Peter
<option value="Bill">Bill
<option value="Carl">Carl
</select>
<br>
<a href="javascript:sortlist()">sort</a>
</form>
like image 33
Pranay Rana Avatar answered Dec 08 '22 00:12

Pranay Rana