How to show <Select> in sorted order

How to sort <option>tag elements <select>using JavaScript?

Here is the HTML that 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> 
+3
source share
4 answers
<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>
+2
source

If the value is different from the text, use the following function to sort them. This is just an updated version of the above solution and will save both the name and the corresponding 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>
+5
source

html-. - , , - ;)

+3

A simpler solution based on Yasser Al-Agl's answer:

function sortList() 
{ 
    var lb = document.getElementById('mylist'); 
    arr = new Array(); 

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

    arr.sort(function(a,b) {
        return (a.text > b.text)? 1 : ((a.text < b.text)? -1 : 0);
    });  // or use localeCompare() if you prefer

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

In short, you only need one array, the elements of which simply refer to the original "options" objects. The sort () function also has the right to choose which property of the property to sort (i.e., the text property, the value property, etc.).

Remember, however, that the "selectedIndex" property of the "select" control can no longer be correct after sorting.

0
source

Source: https://habr.com/ru/post/1759311/


All Articles