Asked 2 years ago
29 Jun 2021
Views 318
Mohamed

Mohamed posted

how to change a selections options based on another select option

how to change a selections options based on another select option
steave

steave
answered Apr 28 '23 00:00

To change the options of one select element based on the selection of another select element using JavaScript, you can use the following approach:


<

select id="first-select">
  <option value="option1">Option 1</option>
  <option value="option2">Option 2</option>
</select>

<select id="second-select">
  <option value="sub-option1">Sub Option 1</option>
  <option value="sub-option2">Sub Option 2</option>
  <option value="sub-option3">Sub Option 3</option>
</select>

<script>
  const firstSelect = document.getElementById('first-select');
  const secondSelect = document.getElementById('second-select');

  // Define the options for the second select element based on the selected option of the first select element
  const optionsMap = {
    option1: ['sub-option1', 'sub-option2'],
    option2: ['sub-option2', 'sub-option3']
  };

  // Set the initial options of the second select element based on the selected option of the first select element
  setSecondSelectOptions();

  // Add an event listener to the first select element that updates the options of the second select element
  firstSelect.addEventListener('change', setSecondSelectOptions);

  function setSecondSelectOptions() {
    const selectedOption = firstSelect.value;
    const options = optionsMap[selectedOption];
    
    // Clear the existing options of the second select element
    secondSelect.innerHTML = '';

    // Add the options for the selected option of the first select element to the second select element
    options.forEach(option => {
      const optionElement = document.createElement('option');
      optionElement.value = option;
      optionElement.textContent = option;
      secondSelect.appendChild(optionElement);
    });
  }
</script>

The example above has two select elements, first-select and second-select. The optonsMap object defines the options for second-select based on the selected option of first-select.

The setSecondSelectOptions function is called initially to set the options of second-select based on the selected option of first-select. Whenever the selected option changes, we call this function again to update the options accordingly.

Inside the setSecondSelectOptions function, we retrieve the selected option of first-select and use it to look up the options for second-select in optionsMap . We then clear the existing options of second-select and add the new options as children of the select element.

You can customize this approach to suit your particular use case.
Post Answer