How can we build a dependent dropdown using chosen?

53 Views Asked by At

I would like to build a dependent dropdown with search feature (I used chosen for the search feature). If any country is selected from the first dropdown the second dropdown should reflect the updated choices related to the first selection.

Example: if India is selected in the first dropdown the second dropdown should have "gurgaon, chennai, bangalore"

$(".dropdown1").chosen({
  maximumSelectionLength: 2,
  max_selected_options: 5
});

$(".dropdown2").chosen({
  maximumSelectionLength: 2,
  max_selected_options: 5
});

$(document).ready(() => {
  $('.dropdown1').on('change', dependentDropdown);
  $('.dropdown1').on('change', myFunction);
});

function myFunction() {
  console.log(document.getElementById("dropdown1").value)
}

function dependentDropdown() {
  var $countriesDropdown = $("#dropdown1"),
    $citiesDropdown = $("#dropdown2");
  
  $countriesDropdown.on("change", function() {
    var _rel = $(this).val();
    console.log(_rel);
    
    $citiesDropdown.find("option").attr("style", "");
    $citiesDropdown.val("");
    
    if (!_rel) return $citiesDropdown.prop("disabled", true);
    
    $citiesDropdown.find("[rel~='" + _rel + "']").show();
    $citiesDropdown.prop("disabled", false);
  });
}
.whole-container {
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-gap: 20px;
  width: 100%;
}

.dp {
  margin: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.8.7/chosen.jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.4.2/chosen.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.1/js/select2.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.1/css/select2.min.css" />

<p>Select a value from the list:</p>

<div class="whole-container">
  <div class="dp">
    <select id="dropdown1" class="dropdown1" name="dropdown1" multiple="false" style="width: 200px;">
      <option value="india">india</option>
      <option value="usa">usa</option>
    </select>
  </div>
  
  <div class="dp">
    <select name="dropdown2" class="dropdown2" id="dropdown2" multiple="false" style="width: 200px;" disabled="disabled">
      <option rel="india" value="gurgaon">gurgaon</option>
      <option rel="india" value="chennai">chennai</option>
      <option rel="india" value="bangalore">bangalore</option>
      <option rel="usa" value="waltham">waltham</option>
      <option rel="usa" value="chicago">chicago </option>
      <option rel="usa" value="wasgington d c">washington d c</option>
    </select>
  </div>
</div>

0

There are 0 best solutions below