Jean
Jean

Reputation: 83

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

Upvotes: 0

Views: 152

Answers (1)

Anton
Anton

Reputation: 2713

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

Upvotes: 1

Related Questions