Reputation: 444
I have a table in HTML and I am trying to get the values from the table and put them into a 2 dim array in javascript. To do this I am trying to use jQuery. I am able to get the indices to work, but then when I try to put values into the array I only get the values for the first row and then I am getting the error of "Uncaught TypeError: Cannot set property '0' of undefined" after the first row.I believe it has to do with this line of code:
tblinfo[i][j] = $(this).text();
example html
<table id="create">
<tr>
<td> row 1 col 1 </td>
<td> row 1 col 2</td>
</tr>
<tr>
<td> row 2 col 1 </td>
<td> row 2 col 2</td>
</tr>
the rest of my j Query Code
$("#save").click(function(){
var tblinfo = new Array(new Array());
$("#create tr").each(function(i){ //go through each row
$(this).find("td").each(function(j){ //go through each column
tblinfo[i][j] = $(this).text();
})
})
alert(tblinfo);});
Thank you very much!
Upvotes: 0
Views: 388
Reputation: 43795
You have already created an array for the first row, but not any others. You need to create an array for each row, otherwise, tblinfo[i]
will be undefined. Also note the preferred array syntax of []
rather than new Array()
. Rather than creating the array in advance, just create it in the row loop as needed:
$("#create tr").each(function(i){ //go through each row
tblinfo[i] = []; //now you can add [j] to this in the next loop
Upvotes: 2