1

This question can be a duplicate.

I need add 24 rows in a html table with 8 columns on click of button. I look for some examples, and I tried this (code below), but only row is add. Someone could help? Thanks for attention.

function addRow(tableID) {

        var table = document.getElementById(tableID);


        var rowCount = 3;


        for (var i = 0; i < 24; i++) {
            var row = table.insertRow(rowCount);    

            var cell1 = row.insertCell(i);
            var element1 = document.createElement("input");
            element1.type = "checkbox";
            element1.name="chbx";


            var element2 = document.createElement("label");

            if (i < 9) {
                element2.innerHTML = "0" + i ;  
            }
            else {
                element2.innerHTML = i; 
            }

            element2.name="lbl";

            cell1.appendChild(element1);
            cell1.appendChild(element2);


            var cell2 = row.insertCell(i + 1);
            cell2.innerHTML = "2";

            var cell3 = row.insertCell(i + 2);
            cell3.innerHTML = "3";

            var cell4 = row.insertCell(i + 3);
            cell4.innerHTML = "4";

            var cell5 = row.insertCell(i + 4);
            cell5.innerHTML = "5";

            var cell6 = row.insertCell(i + 5);
            cell6.innerHTML = "6";

            var cell7 = row.insertCell(i + 6);
            cell7.innerHTML = "7";

            var cell8 = row.insertCell(i + 7);
            cell8.innerHTML = "8";

            rowCount++;
        }
    }
2
  • 1
    Show us the HTML you're using. Better yet, make a jsFiddle. Commented Dec 4, 2014 at 19:01
  • You are using 'i' as the index of where the cell should be inserted, but you are also using 'i' in your for loop for adding rows. Remove 'i' from your row.insertCell calls and replace it with the index (0-7). Commented Dec 4, 2014 at 19:02

1 Answer 1

1

Check out this approach:

JS

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

function addRows(table, rows, columns){
    var row = '';

  for (var i = 0; i < rows; i++){
    row = '<tr>';
   for(var j = 0; j < columns; j++){
     row += '<td>' + j +'</td>'
   }
    row += '</tr>';
    table.innerHTML += row
  }
}

addRows(table, 24, 8);

HTML

<table id="table">
</table>

Check out this codepen.

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

Comments

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.