Home » Jquery » javascript – how can I dynamically fill the other selections with the only options that have the same id?-Exceptionshub

javascript – how can I dynamically fill the other selections with the only options that have the same id?-Exceptionshub

Posted by: admin February 24, 2020 Leave a comment

Questions:

if I had three selections dropdown, and I select an option in one of the three selections, how can I dynamically fill the other selections with the only options that have the same id?

How to&Answer:

Let’s say you want to create a 2 dropdowns to select a car brand and populate the second one with the corresponding cars models.

First, you need an array (or dataset) that contains all brands. Then, you should populate the dropdowns with that data.

const models = [{
    0: 'Uno',
    1: 'Eco Sport'
  },
  {
    0: 'Camaro',
    1: 'Prisma'
  },
  {
    0: 'i10',
    1: 'i20'
  }];

const selectBrands = document.getElementById('brands');
const selectModels = document.getElementById('models');

// Add an change event listener into the brands' select
selectBrands.addEventListener('change', (event) => {
  const brandId = event.target.value;
  const brandModels = models[brandId];
  
  // Clear the input
  selectModels.innerHTML = '<option value="">Select a model</option>';
  
  // Populate the input with the corresponding brand models
  Object.keys(brandModels).forEach((idx) => {
    const option = document.createElement('option');
    option.text = brandModels[idx];
    selectModels.options.add(option);
  });
  
});
<select name="brands" id="brands">
  <option value="">Select a brand</option>
  <option value="0">Fiat</option>
  <option value="1">GM</option>
  <option value="2">Hyundai</option>
</select>
<br />
<select name="models" id="models">
  <option value="">Select a model</option>
</select>

If you need a 3rd dropdown, just repeat the same approach used to make the relation between the 1st and the 2nd one.