简体   繁体   中英

Dropdown and checkboxes field alphabetic order

I have a form and I would like to sort my dropdown and checkboxes field in alphabetic order. I tried to use a javascript but it is not working.

    $(function() {
    var select = $('select');
    select.html(select.find('option').sort(function(x, y) {
    return $(x).text() > $(y).text() ? 1 : -1;
    }));

    // $('select').get(0).selectedIndex = 0;
    });

Thank you for your help

It seems we have answer here: click .

I'll copy a part of it:

var options = $('select option');
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);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM