Sort Select Options by Value Attribute Using jQuery

后端 未结 3 667
终归单人心
终归单人心 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;
    });
    
    0 讨论(0)
  • 2020-12-14 11:12

    const sort = (arr, p, o = "asc") => arr.sort((a, b) => {
      if (o !== "asc")[a, b] = [b, a];
      const isNum = typeof b[p] === "number";
      return (isNum ? Number(a[p]) - b[p] : String(a[p]).localeCompare(b[p]));
    });
    
    
    $.fn.sortChildren = function(op) {
      op = $.extend({
        by: "textContent",
        order: "asc"
      }, op);
      return this.each(function() {
        const i = $(this).prop("selectedIndex");
        $(this).html(sort($(this).children(), op.by, op.order)).prop({selectedIndex: i});
      });
    };
    
    
    // 1. example: sorting by value, order "asc" (default)
    $("#test_1").sortChildren({by: "value"});
    
    // 2. example: sorting by textContent (default), order "desc"
    $("#test_2").sortChildren({order: "desc"});
    <select id="test_1">
      <option value="0.1">dolor</option>
      <option value="a">sit</option>
      <option value="-1">Lorem</option>
      <option value="0">ipsum</option>
      <option value="A">amet</option>
    </select>
    
    <ul id="test_2">
      <li>z</li>
      <li>-20</li>
      <li>ab</li>
      <li>100</li>
      <li>1</li>
      <li>00</li>
      <li>10</li>
      <li>Ab</li>
      <li>0.1</li>
    </ul>
    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

    0 讨论(0)
  • 2020-12-14 11:19
    var selectList = $('#featuredSelectField option');
    
    selectList.sort(function(a,b){
        a = a.value;
        b = b.value;
    
        return a-b;
    });
    
    $('#featuredSelectField').html(selectList);
    

    Here you cand find a demo and compare the results with the original: http://jsfiddle.net/74c2M/3/

    Here you can find the proper code: http://jsfiddle.net/74c2M/4/

    Good luck !

    0 讨论(0)
提交回复
热议问题