I have an array in JavaScript that can go as deep as I want:
var steps = [
{ "step_id" : "1", "step_name" : "Step 1", "children" :
[
{ "step_id" : "4", "step_name" : "Step 4", "children" :
[
{ "step_id" : "6", "step_name" : "Step 6" }
]
},
{ "step_id" : "5", "step_name" : "Step 5" }
]
},
{ "step_id" : "2", "step_name" : "Step 2" },
{ "step_id" : "3", "step_name" : "Step 3" }
];
I then want to show each of the steps in a select drop down box. For every child step, I want to indent it. Here's my JS
function stepsChildren(children, count) {
var new_count = count + 1;
var selection_values_children = '';
for(j=0;j<children.length;j++) {
selection_values_children += '<option value="' + children[j].step_id + '">';
for(x=1;x<=count;x++) {
selection_values_children +=' ';
}
selection_values_children += children[j].step_name + '</option>';
if (typeof(children[j].children) != 'undefined')
selection_values_children += stepsChildren(children[j].children, new_count);
}
return selection_values_children;
}
var selection_values = '';
for(i=0;i<steps.length;i++) {
selection_values += '<option value="' + steps[i].step_id + '">' + steps[i].step_name + '</option>';
if (typeof(steps[i].children) != 'undefined')
selection_values += stepsChildren(steps[i].children, 1);
}
document.write('<select>' + selection_values + '</select>');
This is almost working however in the stepsChildren() function the j variable gets overwritten every time I call it. It's almost like it's setting j as a global variable.
Am I making sense?
If not I've put together a sample for you to look at: http://jsfiddle.net/CJbnm/
If you run the code and look at the select box on the right, notice how Step 5 from the array is missing?
This is because there is only one child of Step 4 which updates the j variable to 1 instead of 2 for the parent function and doesn't show any more results...