Return a filtered list of a second dropdown list that is populated from a database

Viewed 41

I have 2 dropdown lists 1 is populated from the user making selections, the other is populated from the database but the second list gets filtered based on the selection of the first one.

The second list has values coming from the database and when an option is selected from the first dropdown, the code is supposed to check the text of the selection and populate the second list based on the value attached to the text selection for example: Chromatography-Protein A has a value of 1, I want to filter the process parameters that have a value of 1 and display them.
this is what I have tried so far: HTML:

    <select class="form-control form-control-sm" onchange="unitChange(this)" id="unit-operation">
<option selected disabled value="default">Select</option>
<option>Chromatography-Protein A</option>
<option>Chromatography-Mixed Mode</option>
<option>Yes</option>
<select  class="form-control form-control-sm" id="processparameter">
<option selected= "selected" value="default">Select Process Parameter</option>
{% for pp in pp %}
<option value="{{pp.unitoperation_id}}">{{pp.processparameter_name}}</option>
{% endfor %}
</select>
<div class="p-3"></div>
    

JAVASCRIPT:

    $(document).ready(function() {
    var options = $("#processparameter").html();
    $("#unit-operation").change(function(e) {
    var text = ($(this).find("option:selected").text());
    alert(text);
    $("#processparameter").html(options);
    if(text === "Chromatography-Protein A"){

    }
    });

    });
    


    
1 Answers

You can use filter to filter options of second select-box. So , you first need to hide all options and then use filter and check if the value is 1 then show that options only .

Demo Code :

$("#unit-operation").change(function(e) {
  var text = ($(this).find("option:selected").text());
  //if index denotes the value 1,2,3..
  var filter = $(this).find("option:selected").index()
  // if (text === "Chromatography-Protein A") {
  $('#processparameter option:not(:first)').hide(); //hide all not first
  $('#processparameter option:not(:first)').filter(function() {
    return $(this).val() == filter //or 1
  }).show() //show them
  //  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select class="form-control form-control-sm" id="unit-operation">
  <option selected disabled value="default">Select</option>
  <option>Chromatography-Protein A</option>
  <option>Chromatography-Mixed Mode</option>
  <option>Yes</option>
</select>
<select class="form-control form-control-sm" id="processparameter">
  <option selected="selected" value="default">Select Process Parameter</option>
  <option value="1">P1</option>
  <option value="2">P2</option>
  <option value="3">P3</option>
  <option value="1">P11</option>
</select>

Related