I need to create a complex cascading dropdown list using jQuery. This is the issue. I have several states and its respective counties. The first dropdown will show the states and the second will only show the counties for that selected state. This I have it already figured out using these link (and another ones that I don't remember right now):
How to populate a cascading Dropdown with JQuery
Three dimensional Javascript array
The issue now is that I need to add another dimension to the array. I have state, county, and the county code.
I was planing to use something like:
var states = [];
states.push({ name:"AL", counties: [] });
states.push({ name:"AK", counties: [] });
states[0].counties.push({ name:"Autauga", code: [1] });
states[0].counties.push({ name:"Baldwin", code: [3] });
states[1].counties.push({ name:"Aleutian Islands", code: [10] });
states[1].counties.push({ name:"Anchorage", code: [20] });
states[1].counties.push({ name:"Bethel", code: [50] });
function populateDropdown(drop, items) {
drop.empty();
for(var i = 0; i < items.length; i++) {
drop.append('<option value=' + i + '>' + items[i].name + '</option>');
}
drop.show();}
populateDropdown( $('#state'), states);
$('#state').change(function () {
var stateIndex = $(this).val();
var state = states[stateIndex];
populateDropdown($('#county'), state.counties);
});
or this version (I think the code would be easier to read this way)
var states = new Array();
states[0]="AL|Autauga|1";
states[0]="AL|Baldwin|3";
states[1]="AK|Aleutian Islands|10";
states[1]="AK|Anchorage|20";
states[1]="AK|Bethel|50";
And then somehow use .split("|") to separate them. Again, the State-County relation works using the first vesion. What I need to be able to extract the code of the selected county to use it somewhere else, possible for a nother dropdown list. This may look like a simple question for some of you, but I'm just learning JS.
Thanks!