You can store the options if the user selects "Toyota" and the options if the user selects "Nissan" in an array, then attach a change
event listener to the select
that checks its value.
If the value is "Toyota
", iterate through the "Toyota" array and append an option with the value and content set to the item. Otherwise, loop through the "Nissan" array.
const toyotaOptions = ['MarkX', 'Avensis'];
const nissanOptions = ['bluebird', 'Murano', 'Tiida'];
function updateCarByBrand() {
carselect.innerHTML = "";
if (brandselect.value == "Toyota") {
toyotaOptions.forEach(e => carselect.innerHTML += `<option value=${e}">${e}</option>`)
} else {
nissanOptions.forEach(e => carselect.innerHTML += `<option value=${e}">${e}</option>`)
}
}
brandselect.addEventListener('change', updateCarByBrand);
updateCarByBrand();
<p>Manufacturer <br>
<select id="brandselect">
<option value="Toyota"> Toyota</option>
<option value="Nissan"> Nissan</option>
</select>
</p>
<p>Make <br>
<select id="carselect">
</select>
</p>
Or a more customizable and scalable solution:
const options = {
'Toyota': {
cars: ['MarkX', 'Avensis']
},
'Nissan': {
cars: ['bluebird', 'Murano', 'Tiida']
}
}
function updateCarByBrand() {
carselect.innerHTML = "";
options[brandselect.value].cars.forEach(e => carselect.innerHTML += `<option value=${e}">${e}</option>`)
}
brandselect.addEventListener('change', updateCarByBrand);
updateCarByBrand();
<p>Manufacturer <br>
<select id="brandselect">
<option value="Toyota"> Toyota</option>
<option value="Nissan"> Nissan</option>
</select>
</p>
<p>Make <br>
<select id="carselect">
</select>
</p>