Depend dropdown bootstrap-select

You need to loop through items select options but in your current code you are checking the option of both select-boxes hence the values which do not have required class are getting hidden from category select-box as well .Instead change $('option') to $('#items option') and then onces value is change you can set some default option as selected using .val("default").trigger('change') to items select-box.

Demo code :

$("#category").change(function() {
  var category = $(this).val();
  //loop through second selects options
  $('#items option').each(function() {
  //if option has default class
    if ($(this).hasClass(category) || $(this).hasClass("default")) {
      $(this).show();
    } else {
      $(this).hide();
    }
  });

  $('.selectpicker').selectpicker("refresh");
  $('#items').val("0").trigger('change');//set default value as selected


});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.18/css/bootstrap-select.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.18/js/bootstrap-select.min.js"></script>

<select class="selectpicker" id="category">

  <option value="1"> Fruit </option>

  <option value="2"> Animal</option>

</select>

<select class="selectpicker" id="items">
  <!--added this just to keep default value selcted-->
  <option class="default" value="0"> --Select-- </option>
  <option class="1" value="1"> Banana </option>

  <option class="1" value="2"> Apple </option>

  <option class="2" value="3"> Cat </option>

  <option class="2" value="4"> Dog</option>

</select>

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top