0

I am trying hard to loop through the table cells and insert the values inside them.But i don't know what is wrong with my code.Please help me out.I know there is some silly mistake.Please let me know what it is. Here is my code-

 var data = response.datas.length;
              var table = document.getElementById('itemsval');
              for(var i=0; i<data; i++ ){
                var row = table.insertRow(i);
                for(var j=0; j<7; j++){
                 var cell = row.insertCell(j);


                cell[i][j].innerHTML = response.datas[i].p_name;
                 cell[i][j].innerHTML = response.datas[i].p_details;
                 cell[i][j].innerHTML = response.datas[i].p_qty;
                 cell[i][j].innerHTML = response.datas[i].p_rate;
                 cell[i][j].innerHTML = response.datas[i].p_dis;
                 cell[i][j].innerHTML = response.datas[i].p_tax;
                 cell[i][j].innerHTML = response.datas[i].p_tot; 
                }

              }

I keep getting the error- Cannot read property '0' of undefined

Thanks in advance.

payal_suthar
  • 355
  • 8
  • 31

1 Answers1

0

On the first iteration, this line

cell[i][j].innerHTML = response.datas[i].p_name;

tries to access a property called 0 within cell. cell won't have a property called 0 (from the variable i). If it did, that property's value wouldn't have a property with the name 0 (from the variable j) either.

Separately, repeated writing to the same place:

cell[i][j].innerHTML = response.datas[i].p_name;
cell[i][j].innerHTML = response.datas[i].p_details;

...will cause later values to overwrite earlier values.

Instead, you want to add a cell to the row as you go, and set that cell's content. Let's give ourselves a handy function to do that:

function addCell(row, content) {
    var cell = row.insertCell();
    cell.appendChild(
        document.createTextNode(content)
    );
    return cell;
}

That adds the cell, sets its content in a way where you don't have to worry about HTML markup, and returns the cell.

Now, let's use it in your code:

// Get the table
var table = document.getElementById('itemsval');

// Add the rows
response.datas.forEach(function(entry) {
    var row = table.insertRow();
    addCell(row, entry.p_name);
    addCell(row, entry.p_details);
    addCell(row, entry.p_qty);
    addCell(row, entry.p_rate);
    addCell(row, entry.p_dis);
    addCell(row, entry.p_tax);
    addCell(row, entry.p_tot); 
});

Note how that code loops through the response.datas array via Array#forEach. You have lots of other options (that's also an answer of mine), but it seems the simplest in this case.

Community
  • 1
  • 1
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • 1
    this is awesome...it saved my day...thanks a lot for that explanation.thanks buddy...u mind giving me tutions???Just kidding..anyways thanks – payal_suthar Sep 29 '16 at 18:35