1

I am new to JQuery and I am trying to append rows to an existing table.

  1. What is wrong about the code?

  2. How can I insert an empty row without specifying the values in the columns?

  3. Is there a better way to do this? How?

$(document).ready(function () {    
    var tbl = $('#mytable');
    appendTableRow(tbl)
  });
  
  function appendTableRow(table) {      
   var newrow = '';

   newrow += "<tr>";
   newrow += "<td>21</td>";
   newrow += "<td>22</td>";
   newrow += "</tr>";
       
   table.find('tbody tr:last').append(newrow);     
  }
table {
  border-collapse: collapse;
 }

 table td {
  border: 1px solid black;
 }  
  
  table th {
  border: 1px solid black;
 }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="mytable">
   <thead>
  <th>Col1</th>
  <th>Col2</th>
   </thead>
   
   <tbody>
  <tr>
    <td>11</td>
    <td>12</td>
  </tr>
   </tbody>
 </table>
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Elio Fernandes
  • 1,335
  • 2
  • 14
  • 29
  • 2
    Do not append to table row, so **NOT** `table.find('tbody tr:last').append(newrow); `, but to table body: `table.find('tbody').append(newrow); `. – skobaljic Oct 02 '17 at 11:28
  • 1
    Possible duplicate of [How do you append rows to a table using jQuery?](https://stackoverflow.com/questions/2160890/how-do-you-append-rows-to-a-table-using-jquery) – krishnar Oct 02 '17 at 11:32

2 Answers2

0

1) Nothing is wrong, it's doing what it's written to do. Programmatically, it's working fine.

(I almost feel this is a trick question)

2) Instead of newrow += "<td>21</td>"; use newrow += "<td> </td>"; ?

3) Is there a better way to do this? How?

^ These types of questions are off-topic on here.

ProEvilz
  • 5,310
  • 9
  • 44
  • 74
  • This was not a trick question! If you run the code you will see that no new row was created. The two cells created were join next to the 1st row. – Elio Fernandes Oct 02 '17 at 13:09
0

Your code is fine. Just append to tbody.

$(document).ready(function () {    
    var tbl = $('#mytable');
    appendTableRow(tbl)
  });
  
  function appendTableRow(table) {      
   var newrow = '';

   newrow += "<tr>";
   newrow += "<td>21</td>";
   newrow += "<td>22</td>";
   newrow += "</tr>";
       
   $('tbody').append(newrow);     
  }
table {
  border-collapse: collapse;
 }

 table td {
  border: 1px solid black;
 }  
  
  table th {
  border: 1px solid black;
 }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="mytable">
   <thead>
  <th>Col1</th>
  <th>Col2</th>
   </thead>
   
   <tbody>
  <tr>
    <td>11</td>
    <td>12</td>
  </tr>
   </tbody>
 </table>
user1735921
  • 1,359
  • 1
  • 21
  • 46