I trying to collect information from the user based on a 2D array. I have problems passing on the 2D array from one function in Javascript to another function, as an array and not as text. What could I be doing wrong?
The array is this
Title Category1 Category2 Category3
Category1 Apples Blue Eyes
Category2 Oranges Green Legs
Category3 Pairs Yellow Arms
Mango Gray
The idea is to display Column1 first by having the "Title" as text and the Category list by buttons. On click of a button it should display the contents of the respected column. If, therefore, the user clicks on Category3, he should see Category3 as text and the options "Eyes", "Legs", "Arms" as buttons.
My problem is passing on the onclick the correct parameters as nextStep(this,database) is not working. When I pass on nextStep(this,\''+database+'\') of course it passes on the "database" as text and not as an array.
Any suggestions?
My HTML is a simple div.
<div id="mainPage"></div>
My Javascript starts on load...
window.addEventListener("load", starting, false);
function starting(){
var database = [[Title, Category1, Category2, Category3], [Category1,Apples,Blue,Eyes],[Category2,Oranges,Green,Legs],[Category3,Pairs,Yellow,Arms],[,Mango,Gray,]];
renderCategories(database,1);
}
function renderCategories(database, pos){
mainPage = document.getElementById("mainPage");
var catTitles = database[0];
var catTitle = catTitles[pos];
var allmainPage = database[2];
mainPage.innerHTML = '<div class="input-field col s12 m12"><h3>'+catTitle+'</h3></div>';
for(var i=0; i<allmainPage.length; i++){
var categoryListValue = allmainPage[i][pos];
if (categoryListValue !=""){
mainPage.innerHTML += '<div class="row"><button onclick="nextStep(this,database)" value="'+categoryListValue+'">'+categoryListValue+'</button></div>';
}
}
}
function nextStep(selection, database){
var selectedCat = selection.value;
alert(selectedCat);
var catTitles = database[0];
alert(catTitles);
}
window.addEventListener("load", starting, false);
onclick="...", you have much more control over the element and its listener if you create the element (elem = document.createElement('div')) and then assign the listener with JS, like:elem.onclick = ...allmainPageis one dimensional, you are treating it as if it had two dimensions