0

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!

2
  • try alerting i and j in the loop and see what the values are. Commented Jan 17, 2014 at 1:11
  • The i and j's we actually working, but when I put that line of code that I had above I got the error. Commented Jan 17, 2014 at 1:16

1 Answer 1

2

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

Live demo (click).

Sign up to request clarification or add additional context in comments.

1 Comment

That did it! Thanks. I can't believe it was that simple.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.