简体   繁体   中英

Select2 Change Event - Change the options for next select2 box on first select2 box value change

I have 2 select2 boxes. First is Category and next is Sub-category.

Now, I want to change the options for subcategory box based on Category box selected value. And the data for Subcategory box should load using AJAX.

Please help me.

just solved it myself

<link href="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/css/select2.min.css" rel="stylesheet" />
<script src="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/js/select2.min.js"></script>

<select class="js-data-example-ajax" id="category" >
<option value="">Select a category</option>
<option>cat1</option>
<option>cat2</option>
<option>cat3</option>
</select>
<select class="js-data-example-ajax" id="sub-category" >
</select>
<script>
  $("#category").select2({
  placeholder: "Select a category",allowClear: true
  });

  $("#sub-category").select2({
  placeholder: "Select sub-category",allowClear: true
  });


  $('#category').on("change", function (e) { 
   var result = '';
   var catval = $(this).val();
    if(catval != '') {
     url = "subcats_top/"+ catval;
        $.ajax({
        type: "GET",
        url: url,
        dataType: 'json',
        success: function(data){
        var length = data.length;

        if(length > 0) {
            for(key in data) {
                result += '<option value="' + data[key].id + '">' + data[key].name + '</option>';
            }


        } else {

        }
        $("#sub-category").html(result);
    }
    });
  }
   });
    </script>

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