JSFiddle - React, Tailwind, and code Playground

by Harmonix Motion

HTML

<label for="first_dropdown">First Dropdown</label><br>
<select id='first_dropdown'>
  <option value="" disabled selected>Choose</option>
  <option value="ab">ab</option>
</select>

<br>
<br>
<label for="second_dropdown">Second Dropdown</label><br>
<select id="second_dropdown">
  <option value="" disabled selected>Choose</option>
</select>

<br>
<br>

<label for="third_dropdown">Third Dropdown</label><br>
<select id="third_dropdown">
  <option value="" disabled selected>Choose</option>
</select>

JavaScript

// Get first dropdown
let firstDropdown = document.getElementById('first_dropdown');

// When a value is selected in the first dropdown
firstDropdown.addEventListener('change', function() {

// Get value chosen by the user
let firstDropdownValue = firstDropdown.options[firstDropdown.selectedIndex].value;

if (firstDropdownValue == 'ab') {

  // Add the values in the second dropdown based on the value selected in the first dropdown
  let secondDropdown = document.getElementById('second_dropdown');
  let option_1 = document.createElement('option');
  option_1.value = 'a';
  option_1.innerHTML = 'a';
  secondDropdown.appendChild(option_1);

  let option_2 = document.createElement('option');
  option_2.value = 'b';
  option_2.innerHTML = 'b';
  secondDropdown.appendChild(option_2);
  }
});

// Get second dropdown
let secondDropdown = document.getElementById('second_dropdown');

// When a value is selected in the first dropdown
secondDropdown.addEventListener('change', function() {

// Get value chosen by the user
let secondDropdownValue = secondDropdown.options[secondDropdown.selectedIndex].value;

if (secondDropdownValue == 'a') {

  // Add the values in the second dropdown based on the value selected in the first dropdown
  let thirdDropdown = document.getElementById('third_dropdown');
  let option_1 = document.createElement('option');
  option_1.value = 'aa';
  option_1.innerHTML = 'aa';
  thirdDropdown.appendChild(option_1);

  let option_2 = document.createElement('option');
  option_2.value = 'aaa';
  option_2.innerHTML = 'aaa';
  thirdDropdown.appendChild(option_2);
  }
});