Home > Mobile >  how to change the option in dropdown 2 if selected value in dropdown 1
how to change the option in dropdown 2 if selected value in dropdown 1

Time:10-20

I want that when I select a value from dropdown 1, it changes the option in the dropdown 2

For example: if I choose 'plant 2 o plant 3' from 'dropdown 1', then in 'dropdown 2' it should change automatically to the 'other option'. with only 2 dropdowns

Can anyone help-me please? I thank you in advance!

here's my DEMO

[Demo][1]

<select name="" id="">
  <option value="">Select</option>
  <option value="">plant 1</option>
  <option value="">plant 2</option>
  <option value="">plant 3</option>

</select>

<select name="" id="">
   <option value="">Select</option>
   <option value="">outside 1</option>
   <option value="">inside 1</option>
</select>
//other option is 
//outside 2/3
//inside 2/3


  [1]: https://jsfiddle.net/Tafreets/68k2pvg3/

CodePudding user response:

I can think of two options. First option is to use change event on first dropdown then read the selected value, empty the 2nd dropdown and then have if/else or switch statement to add options to 2nd dropdown : Demo

$('#plantType').on('change', function() {
    var actionDrop = $("#location");
    actionDrop.empty();
    switch(this.value) {
      case 'plant1':
        actionDrop.append($('<option>', {value:'outside1', text:'outside 1'}));
        actionDrop.append($('<option>', {value:'inside1', text:'inside 1'}));
        break;
      case 'plant2':
        actionDrop.append($('<option>', {value:'outside2', text:'outside 2'}));
        actionDrop.append($('<option>', {value:'inside2', text:'inside 2'}));
        break;
    }
    
  });

Second option have separate dropdown elements. when user selects from first dropdown then show and hide dependent dropdowns based on the selection using javascript or Jquery : Demo

$('#plantType').on('change', function() {
  $('.location').hide();
  if (this.value==="plant1"){
     $('#plant1Location').show()
  }else if(this.value==="plant2"){
    $('#plant2Location').show()
  }
});
  • Related