Sunday, May 12, 2024
 Popular · Latest · Hot · Upcoming
68
rated 0 times [  71] [ 3]  / answers: 1 / hits: 8986  / 7 Years ago, sat, january 28, 2017, 12:00:00

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?


More From » jquery

 Answers
1

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>




[#23262] Thursday, January 26, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
terrellhunterm

Total Points: 82
Total Questions: 109
Total Answers: 98

Location: Vietnam
Member since Sun, Oct 18, 2020
4 Years ago
;