Asked 2 years ago
29 Jun 2021
Views 262
Hailee

Hailee posted

Change select box value depending other selected option box

Change select box value depending other selected option box
pratik

pratik
answered Apr 28 '23 00:00

To change the options of a select box based on the selected value of another select box, you can use jQuery to listen for the change event on the first select box, and then update the options of the second select box accordingly. Here's an example:



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

<select id="second-select">
  <option value="a">Option A</option>
  <option value="b">Option B</option>
  <option value="c">Option C</option>
</select>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
  $(document).ready(function() {
    // Listen for the change event on the first select box
    $('#first-select').change(function() {
      // Get the selected value of the first select box
      var selectedValue = $(this).val();
      
      // Update the options of the second select box based on the selected value
      if (selectedValue == '1') {
        $('#second-select').html(`
          <option value="a">Option A</option>
          <option value="b">Option B</option>
        `);
      } else if (selectedValue == '2') {
        $('#second-select').html(`
          <option value="x">Option X</option>
          <option value="y">Option Y</option>
          <option value="z">Option Z</option>
        `);
      } else {
        $('#second-select').html(`
          <option value="p">Option P</option>
          <option value="q">Option Q</option>
          <option value="r">Option R</option>
        `);
      }
    });
  });
</script>

In this example, we have two select boxes with the ids first-select and second-select. When the selected value of the first select box changes, we use the val () method to get the selected value, and then update the options of the second select box based on that value.

To update the options of the second select box, we use the html () method to set the inner HTML of the select box to a new set of option elements. We use if/else statements to determine which options to show based on the selected value of the first select box.

Note that you can customize this approach to fit your specific use case.
Post Answer