Reputation: 87
I have two dropdown menus as follows:
<form id="dynamicForm">
<select id="A">
</select>
<select id="B">
</select>
</form>
And I have a dictionary object where the keys are the options for A
and the values, B
are arrays corresponding to each element in A
, as follows:
var diction = {
A1: ["B1", "B2", "B3"],
A2: ["B4", "B5", "B6"]
}
How can I dynamically populate the menu B based on what the user selects in menu A?
Upvotes: 4
Views: 10024
Reputation: 115282
Bind a change event handler and populate second select tag based on selected value.
var diction = {
A1: ["B1", "B2", "B3"],
A2: ["B4", "B5", "B6"]
}
// bind change event handler
$('#A').change(function() {
// get the second dropdown
$('#B').html(
// get array by the selected value
diction[this.value]
// iterate and generate options
.map(function(v) {
// generate options with the array element
return $('<option/>', {
value: v,
text: v
})
})
)
// trigger change event to generate second select tag initially
}).change()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="dynamicForm">
<select id="A">
<option value="A1">A1</option>
<option value="A2">A2</option>
</select>
<select id="B">
</select>
</form>
Upvotes: 4
Reputation: 31712
This will dynamically populate both select
s:
var diction = {
A1: ["B1", "B2", "B3"],
A2: ["B4", "B5", "B6"]
};
// the function that will populate the select
function populateSelect(id, values) {
// get the select element
var $select = $(id);
// empty it
$select.empty();
// for each value in values ...
values.forEach(function(value) {
// create an option element
var $option = $("<option value='" + value + "'>" + value + "</option>");
// and append it to the select
$select.append($option);
});
}
// when the #A select changes ...
$("#A").on("change", function() {
// get the value of the selected element (the key)
var key = $(this).val();
// populate #B accordingly
populateSelect("#B", diction[key]);
});
// Before anything, populate #A with the keys of diction and ...
populateSelect("#A", Object.keys(diction));
// ... #B with whatever #A hold its key
populateSelect("#B", diction[$("#A").val()]);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="dynamicForm">
<select id="A">
</select>
<select id="B">
</select>
</form>
Upvotes: 2
Reputation: 42370
You can create a change listener for the first select box and populate the html of the second select box.
See demo below:
var diction = {
A1: ["B1", "B2", "B3"],
A2: ["B4", "B5", "B6"]
}
$('#A').on('change', function() {
$('#B').html(
diction[$(this).val()].reduce(function(p, c) {
return p.concat('<option value="' + c + '">' + c + '</option>');
}, '')
);
}).trigger('change');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="dynamicForm">
<select id="A">
<option value="A1">A1</option>
<option value="A2">A2</option>
</select>
<select id="B">
</select>
</form>
Upvotes: 3