Reputation: 29
I have two array
array1[1;2;3;]
array2[1;1;1;1;2;2;3;3;]
I filled 1st array in dropdown menu. Now i need to check if in 2nd array is elements with same value "1;" and on select fill dropdown2 with elements of array2 with same value. I just need example of code.
Upvotes: 0
Views: 2231
Reputation: 36
I created a jsFiddle which may help you achieve your goal: http://jsfiddle.net/XTdrr/
The initial HTML:
<select id="select1" onChange="populateSelect2()">
<option value="">Choose...</option>
</select>
<br/>
<select id="select2"></select>
The initial JavaScript variables
var array1 = [1, 2, 3];
var array2 = [1, 1, 1, 1, 2, 2, 3, 3];
var select1 = document.getElementById("select1");
var select2 = document.getElementById("select2");
First, it populates the first dropdown list with the values in array1.
window.onload = function () {
// here we populate select1 with the elements in array1
for (var i = 0; i < array1.length; i++)
{
var opt = document.createElement('option');
opt.value = array1[i];
opt.innerHTML = array1[i];
select1.appendChild(opt);
}
}
When something is selected int the first dropdown, it looks for matching elements in array2 and populates the second dropdown with those.
function populateSelect2()
{
// first, empty select2
for (var i = select2.options.length - 1; i >= 0; i--)
{
select2.remove(i);
}
// then add new items
// based on the selected value from select1 and matches from array2
for (var i = 0; i < array2.length; i++)
{
if (array2[i] == select1.value)
{
var opt = document.createElement('option');
opt.value = array2[i];
opt.innerHTML = array2[i];
select2.appendChild(opt);
}
}
}
Upvotes: 1