JavaScript:在多选中排序选项时忽略大小写

时间:2013-06-11 19:05:45

标签: javascript sorting multi-select case-insensitive

我正在尝试在multiselect中对选项进行排序,而忽略了这种情况。我已经看到了分别完成这些事情的方法,但我不确定如何一起完成它们。

这是我的HTML排序:

<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>

这是我的JavaScript(注意:我不是在寻找jQuery解决方案):

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;
}

以下是jsFiddle

1 个答案:

答案 0 :(得分:2)

您应该覆盖默认排序功能,如下所示:

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

这是ECMAScript Array.sort一般形式:

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;
}