0

I am trying to add a new row to this little table with just one column. Can anybody help? I created a new function for this purpose, for the moment it is not working.

enter image description here

function row_creator() {
  var table = document.getElementById("myTable")[0];
  var newRow = table.insertRow();
  var newCell = newRow.insertCell(0);
  var newText = document.createTextNode('New row');
  newCell.appendChild(newText);
}
row_creator();
table,
th,
td {
  border: 1px solid black;
}
<! --COMIENZO TABLA -->

<table id="MyTable" class="egt">



  <! --PRIMERA LINEA -->

  <tr>
    <th>Source ID</th>
  </tr>

  <! --SEGUNDA LINEA -->

  <tr>
    <td>
      <input type="number" id="fname" name="fname">
    </td>
    <tr>

</table>
Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
Miguel Gonzalez
  • 398
  • 1
  • 12

2 Answers2

2

There are errors in this line document.getElementById("myTable")[0]

  1. getElementById returns a element (not a collection) so no need of [0]
  2. The Id must match your element Id MyTable with capital M
Cedric Cholley
  • 1,956
  • 2
  • 9
  • 15
1

function row_creator() {
  var table = document.getElementById("mytable"); /*not nedd [0] & same name use fore html and js*/
  var newRow = table.insertRow(); /* nedd position of row */
  var newCell = newRow.insertCell();/* add col in table*/
  newCell.innerHTML = "NEW CELL1"; /* to insert data in row [newCell] is var we have define and innerHTML to add html data*/ 
}


setInterval(row_creator, 1000);/* setInterval(className, Time[1000 = 1s]); */
table,
th,
td {
  border: 1px solid black;
}
<table id="mytable" class="egt">
    <! --PRIMERA LINEA -->
    <tr>
        <th>Source ID</th>
    </tr>
    <! --SEGUNDA LINEA -->
    <tr>
        <td>
            <input type="number" id="fname" name="fname">
        </td>
        <tr>
</table>
KashyapVadi
  • 495
  • 4
  • 14