Sort Select Options by Value Attribute Using jQuery

后端 未结 3 681
终归单人心
终归单人心 2020-12-14 10:19

Well, the title says it all. What I am doing is creating a featured product module. The drop down list of sizes is populated using JSON and I am using handlebars to render t

3条回答
  •  清歌不尽
    2020-12-14 11:04

    $(function() {
      // choose target dropdown
      var select = $('select');
      select.html(select.find('option').sort(function(x, y) {
        // to change to descending order switch "<" for ">"
        return $(x).text() > $(y).text() ? 1 : -1;
      }));
    
      // select default item after sorting (first item)
      // $('select').get(0).selectedIndex = 0;
    });
    

提交回复
热议问题