Monday, June 22, 2015

Sort the content of select element using JavaScript

While I was working for the solution to the scenario that I had to copy list of location from one multiple select element to another. I had an issue that those location were not sorting alphabetically.After some googling and playing around, I come up with following solution
function sortSelectElement(selElement) {
    var tmpAry = new Array();
    for (var i=0;i<selElement.options.length;i++) {
        tmpAry[i] = new Array();
        tmpAry[i][0] = selElement.options[i].text;
        tmpAry[i][1] = selElement.options[i].value;
    while (selElement.options.length > 0) {
       selElement.options[0] = null;
    for (var i=0;i<tmpAry.length;i++) {
        var op = new Option(tmpAry[i][0], tmpAry[i][1]);
        selElement.options[i] = op;

Hope it will helps for someone :)