Search code examples
jquerybootstrap-4jquery-selectors

Jquery show not working on select options after hiding


Consider following bootstrap selectpicker:

<select id="parent" class="selectpicker">
<option value="1">Parent 1</option>
<option value="2">Parent 2</option>
</select>

<select id="child" class="selectpicker">
<option value="1">Child - Parent 1</option>
<option value="2">Child - Parent 2</option>
</select>

 $("#parent").on('change', function (e) { 
   var parentId = $(this).val();
   $("#child option").each((i,a) => {
      var childParentId = $(a).value();
      if(childParentId != parentId) {
         $(a).hide();
       } else { $(a).show() }
  });
   $("#child").selectpicker("refresh")
 });

No matther what I do, the $(a).show() has no effect. What I am missing ?


Solution

  • You need to use $(this) to get the dom but not $(a)

    Update: jsfiddle

     $("#parent").on('change', function (e) { 
       var parentId = $(this).val();
       $("#child option").each(function() {
          var childParentId =  $(this).val();
          if(childParentId != parentId) {
              $(this).hide();
           } else { $(this).show() }
      });
       // $("#child").selectpicker("refresh")
     });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <select id="parent" class="selectpicker">
    <option value="1">Parent 1</option>
    <option value="2">Parent 2</option>
    </select>
    
    <select id="child" class="selectpicker">
    <option value="1">Child - Parent 1</option>
    <option value="2">Child - Parent 2</option>
    </select>