-2

I have a little challenge. I saved somethings to my MongoDB and I want to render them with a select tag. The situation is, I want what is selected in the first option to determine what can be selected in the second option, how do I go about it?

<select name="1" id="">
    <option value="">A</option>
    <option value="">B</option>
    <option value="">C</option>
</select>

if option A is selected in 1, 2 should have only the option of
<select name="2" id="">
    <option value="">D</option>
    <option value="">E</option>
    <option value="">F</option>
</select> 
if option B is selected in 1, 2 should have only the option of
<select name="2" id="">
    <option value="">G</option>
    <option value="">H</option>
    <option value="">I</option>
</select>
if option C is selected in 1, 2 should have only the option of
<select name="2" id="">
    <option value="">J</option>
    <option value="">K</option>
    <option value="">L</option>
</select>

1 Answers1

0

In its simplest form, you can create a mapping with your dynamic options and then attach a function your select's onclick handler that will dynamically change the options within the second select based on the selection made to the first select.

let dynamicOptions = {
  A: ['D', 'E', 'F'],
  B: ['G', 'H', 'I'],
  C: ['J', 'K', 'L']
}

function onSelectHandler() {
  let select = document.getElementById("first-select");
  let selectedValue = select.options[select.selectedIndex].value;
  let dynamicSelect = document.getElementById("dynamic-select");

  // Remove all existing options from dynamic select
  while (dynamicSelect.firstChild) {
    dynamicSelect.removeChild(dynamicSelect.firstChild);
  }

  // Get options based on the user's input (selectedValue)
  // and add them to the dynamic select element
  dynamicOptions[selectedValue].forEach(opt => {
    let option = document.createElement("option");
    option.text = opt;
    dynamicSelect.add(option)
  })
}

onSelectHandler()
<div>
  <label for="first-select">Choose an option:</label>
  <select id="first-select" onchange="onSelectHandler();">
    <option value="A">A</option>
    <option value="B">B</option>
    <option value="C">C</option>
  </select>
</div>
<br />
<div>
  <label for="dynamic-select">Choose an option:</label>
  <select id="dynamic-select">
  </select>
</div>
heyitsjhu
  • 951
  • 7
  • 9