次の jQuery を使用して、フォーム内の選択要素を並べ替えています。
$('select.select-sortable').each(function () {
var options = $(this).children();
var arr = options.map(function(_, o) { return { t: $(o).text(), v: o.value }; }).get();
arr.sort(function(o1, o2) { return o1.t > o2.t ? 1 : o1.t < o2.t ? -1 : 0; });
options.each(function(i, o) {
o.value = arr[i].v;
$(o).text(arr[i].t);
});
});
並べ替えは機能しますが、ページが更新されるたびに表示される値が変わります。選択肢がいくつあっても、第1選択肢→第3選択肢→第2選択肢→第1選択肢の順で変化します。
選択を最初のオプションにロックするループに追加$(this).children(":first").attr("selected", true);
しましたが、なぜdsiplayが変更されたのか、なぜその順序で変更されたのかはまだわかりません。誰にもアイデアはありますか?