Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding new row to table using javascript

Tags:

javascript

I have searched and found similar answers to this but not exactly and I can't figure out what I'm doing wrong... Thanks for any help you can provide!

<html><head>
<script>
function doTheInsert() {
  var newRow=document.getElementById('myTable').insertRow();
  newRow="<td>New row text</td><td>New row 2nd cell</td>";
}
</script></head>
<body>
<table id="myTable" border="1">
  <tr>
    <td>First row</td>
    <td>First row 2nd cell</td>
  </tr>
  <tr>
    <td>Second row</td>
    <td>more stuff</td>
  </tr>
</table>
<br>
<input type="button" onclick="doTheInsert()" value="Insert new row"> 
</body></html>
like image 350
Jessica Marks Avatar asked Jan 03 '23 23:01

Jessica Marks


1 Answers

I suppose it would be more formally correct to use insertCell for each added cell, but just dropping in the whole string will work if you set newRow's innerHTML:

function doTheInsert() {
  var newRow=document.getElementById('myTable').insertRow();
  // newRow = "<td>New row text</td><td>New row 2nd cell</td>"; <-- won't work
  newRow.innerHTML = "<td>New row text</td><td>New row 2nd cell</td>";
}

function doTheInsert() {
  var newRow=document.getElementById('myTable').insertRow();
  newRow.innerHTML="<td>New row text</td><td>New row 2nd cell</td>";
}
<table id="myTable" border="1">
  <tr>
    <td>First row</td>
    <td>First row 2nd cell</td>
  </tr>
  <tr>
    <td>Second row</td>
    <td>more stuff</td>
  </tr>
</table>

<input type="button" onclick="doTheInsert()" value="Insert new row"> 
like image 96
Daniel Beck Avatar answered May 29 '23 01:05

Daniel Beck