Reputation: 75
I have two input boxes as dropdown list. The dropdown list to be created for the second input box depends on the value given in the first input field.
var firstarray =[{sym: "1", desc: "one"},
{sym: "2", desc: "two"},
{sym: "3", desc: "three"}];
var secondarray =[{sym: "4", desc: "four", firstarraycode: "2"},
{sym: "5", desc: "five", firstarraycode: "2"},
{sym: "6", desc: "six", firstarraycode: "1"}];
By using the first array I created the dropdown for the first input box.
The sym
value of the first array is the third field (firstarraycode
) of the second input box.
Depending on the sym
value of the first array selection, the second input box's dropdown values must be filtered from the array.
For example, if we select 2
in the first dropdown list, it creates the second drop down list with sym
values 4
and 5
.
Upvotes: 0
Views: 843
Reputation: 9370
Try : http://jsfiddle.net/aF6Xq/
var firstarray =[{sym:"1",desc:"one"},{sym:"2",desc:"two"},{sym:"3",desc:"three"}];
var secondarray =[{sym:"4",desc:"four",firstarraycode:"2"},{sym:"5",desc:"five",firstarraycode:"2"},{sym:"6",desc:"six",firstarraycode:"1"}];
function fillsecond(array){
$('#second').empty();
$('#second').append("<option>Select</option>");
for (i=0;i<array.length;i++){
$('<option/>').val(array[i].sym).html(array[i].desc).appendTo('#second');
}
}
$('#first').append("<option>Select</option>");
$('#second').append("<option>Select</option>");
for (i=0;i<firstarray.length;i++){
$('<option/>').val(firstarray[i].sym).html(firstarray[i].desc).appendTo('#first');
}
$('#first').change(function(){
var val=$(this).val();
var tempArray = $.grep( secondarray, function(elem){ return elem.firstarraycode == val; });
fillsecond(tempArray);
});
Upvotes: 1
Reputation: 171679
There are several jQuery utlities you can use like $.map
or $.grep
to filter the data.
$('#select_one_ID').change(function(){
var val=$(this).val();
var optionsArray=$.grep( secondarray, function(item){ return item.firstarraycode == val; });
/* loop over optionsArray to create new option tags*/
});
API Reference: http://api.jquery.com/jQuery.grep/
Upvotes: 0