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?
Asked
Active
Viewed 28 times
-2
-
1Can you [share with us what you tried out so far](https://stackoverflow.com/help/minimal-reproducible-example)? – Juan Marco Feb 14 '20 at 16:33
-
1https://stackoverflow.com/questions/9454645/does-id-have-to-be-unique-in-the-whole-page The concept has a flaw around "have the same id". **Unique** ids should not repeat, by web standards. – Taplar Feb 14 '20 at 16:35
-
1The question is moot as `id` **have** to be unique within the DOM. – Rory McCrossan Feb 14 '20 at 16:36
-
1Welcome to SO! Please provide the current markup you have as well as code showing what you've tried so far. Have a look at [How-to-ask](https://stackoverflow.com/help/how-to-ask) and, if possible, provide a [MRE](https://stackoverflow.com/help/minimal-reproducible-example). – David Feb 14 '20 at 16:37
1 Answers
0
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.

Cadu De Castro Alves
- 637
- 4
- 11