1

I am trying to sort options in a multiselect while ignoring the case. I have seen methods for doing each of these things separately, but I'm not sure how to do them together.

Here is my HTML for sorting:

<form action="" method="get">
<label for="elliot">select:</label>
<select name="elliot" multiple="multiple" id="elliot1" style="height:140px;display:block;width: 200px;">
<option>d</option>
<option>Z</option>
<option>avery</option>
<option>5</option>
<option>Alive</option>
<option>8</option>
<option>b</option>
</select>
<button type="button" onclick="javascript:sortSelect(elliot1);">Sort</button>
</form>

and here is my JavaScript (note: I am not looking for a jQuery solution):

function sortSelect(selElem) {
    var tmpAry = new Array();
    for (var i=0;i<selElem.options.length;i++) {
        tmpAry[i] = new Array();
        //tmpAry[i][0] = selElem.options[i].text;
        tmpAry[i][0] = selElem.options[i].text;
        tmpAry[i][1] = selElem.options[i].value;
    }
    tmpAry.sort();
    while (selElem.options.length > 0) {
        selElem.options[0] = null;
    }
    for (var i=0;i<tmpAry.length;i++) {
        var op = new Option(tmpAry[i][0], tmpAry[i][1]);
        selElem.options[i] = op;
    }
    return;
}

Here is the jsFiddle

Mr. Hargrove
  • 519
  • 1
  • 6
  • 26
user2219915
  • 289
  • 3
  • 7
  • 19

1 Answers1

3

You should override the default sorting function like this:

tmpAry.sort(
  function (a, b) {
    var _a = a[0].toLowerCase();
    var _b = b[0].toLowerCase();
    if (_a < _b) return -1;
    if (_a > _b) return 1;
    return 0;
});

Fiddle

Here is the ECMAScript Array.sort general form:

function compare(a, b) {
  if (a is less than b by some ordering criterion)
     return -1;
  if (a is greater than b by the ordering criterion)
     return 1;
  // a must be equal to b
  return 0;
}
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132