2

I need to insert some value into html table dynamically. For example, I have some inputs and then I have a table (about 5 rows), so I have one button which enables a timer. When the timer is stopped I need to insert data into table.

Here is the code, how do I add data to one row?

document.getElementById('d1').innerHTML = document.getElementById('ctrl_ball_size_val').value;
document.getElementById('l1').innerHTML = document.getElementById('ctrl_cilindr_height_val').value;
document.getElementById('t1').innerHTML = document.getElementById('stopwatch').value;

How can I add data (data can be different) to the table row by row?

JJJ
  • 32,902
  • 20
  • 89
  • 102
vladimir
  • 695
  • 3
  • 15
  • 34

2 Answers2

1

It is highly recommended to avoid using innerHTML for this task. I suggest to use the DOM to achieve that.

Here is a quick example on how you can create HTML table dynamically using JavaScript:

var tbl = document.createElement("table");

for(var i=0;i<=10;i++){
    var tr = document.createElement("tr");

    for(var j=0;j<=10;j++){
        var td = document.createElement("td");
        td.innerHTML = i*j;
        tr.appendChild(td);
    }
    tbl.appendChild(tr);
}

document.body.appendChild(tbl);

Check out my Live example

Stasel
  • 1,298
  • 1
  • 13
  • 26
0

If you are using JQuery Simply use:

$('#tableID > tbody  > tr').each(function() { //Acess $(this) });

And you Never Need it then?

as per jQuery each loop in table row, just a bit of code:

var table = document.getElementById('tblOne');

var rowLength = table.rows.length;

for(var i=0; i<rowLength; i+=1){
  var row = table.rows[i];

  //your code goes here, looping over every row.
  //cells are accessed as easy

  var cellLength = row.cells.length;
  for(var y=0; y<cellLength; y+=1){
    var cell = row.cells[y];

    //do something with every cell here
  }
}
Community
  • 1
  • 1
internals-in
  • 4,798
  • 2
  • 21
  • 38