Javascript change drop-down box options based on another drop-down box value
11,775
Here is a simple example to get you started.
It works by attaching an event listener for the change
event to the province dropdown, then looks up what towns are in that province via the provs
object.
See the comments for a detailed explanation of what each line does.
window.onload = function() {
// provs is an object but you can think of it as a lookup table
var provs = {
'British Columbia': ['Victoria', 'Sanitch'],
'Ontario': ['Bracebridge', 'Waterloo']
},
// just grab references to the two drop-downs
prov_select = document.querySelector('#prov'),
town_select = document.querySelector('#town');
// populate the provinces drop-down
setOptions(prov_select, Object.keys(provs));
// populate the town drop-down
setOptions(town_select, provs[prov_select.value]);
// attach a change event listener to the provinces drop-down
prov_select.addEventListener('change', function() {
// get the towns in the selected province
setOptions(town_select, provs[prov_select.value]);
});
function setOptions(dropDown, options) {
// clear out any existing values
dropDown.innerHTML = '';
// insert the new options into the drop-down
options.forEach(function(value) {
dropDown.innerHTML += '<option name="' + value + '">' + value + '</option>';
});
}
};
<select id="prov"></select>
<select id="town"></select>
Related videos on Youtube
Author by
arreojn
Updated on June 04, 2022Comments
-
arreojn almost 2 years
I am practising programming in JavaScript and I have found a problem that must be answered by some experts regarding
drop-down
boxes.The Scenario is:
I have a
drop-down
box that gives some possible options for provinces and also a second one (town) which depends only on what is selected in the provincesdrop-down
.Is there a way in JavaScript that when I chose among provinces, the second
drop-down
gives the options from the province selected?-
meskobalazs about 9 yearsHave you tired anything?
-
MuppetGrinder about 9 yearsI think "must be answered by experts" is a bit strong, google could have probably got you there
-
MrKekson about 9 yearsYo can find the answer here allready: stackoverflow.com/questions/5686735/… Alltrough, i would use Jquery for simplicity.
-