Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add rows in HTML Table using Jquery?

I want to add rows dynamically at runtime using Jquery. At beginning table don't have any records. When user click the ADD Button it has to add the rows. Watch this picture

When user click ADD Button the operator dropdown list box value and Filter values should add in that table row.

Here what I tried Jquery CODE

$("#btnAdd").click(function () {

   // $("#queryTable tr:last").after("<tr>...</tr><tr>...</tr>");
    $('#queryTable > tbody:last-child').append('<tr>Record1</tr><tr>Record2</tr>');
});

I tried both lines. But it doesn't make any sense. Thanks

HTML Code

 <table class="table table-hover " id="queryTable">
     <thead>
         <tr>
             <th>Field Name</th>
             <th>Values</th>
         </tr>
     </thead>
     <tbody>
         <tr>
             <td>Mark</td>  //Please ignore these two records. At beginning the table will be empty
             <td>Otto</td>
         </tr>
         <tr>
             <td>Jacob</td>
             <td>Thornton</td>
         </tr>
     </tbody>
 </table>

2 Answers

The correct jQuery code to add HTML elements is:

$('#queryTable tbody').append('<tr><td>Record1</td><td>Record2</td></tr>');
like image 84
Kevin Jimenez Avatar answered Dec 07 '25 21:12

Kevin Jimenez


Your input string HTML is incorrect. As of now you have no TD element thus content is not displayed. However its appended and exists in DOM

'<tr><td>Record1</td><td>Record2</td></tr>

instead of

'<tr>Record1</tr><tr>Record2</tr>'

$('#queryTable > tbody:last-child').append('<tr><td>Record1</td><td>Record2</td></tr>');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<table class="table table-hover" id="queryTable">
  <thead>
    <tr>
      <th>Field Name</th>
      <th>Values</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Mark</td>
      <td>Otto</td>
    </tr>
    <tr>
      <td>Jacob</td>
      <td>Thornton</td>
    </tr>
  </tbody>
</table>
like image 35
Satpal Avatar answered Dec 07 '25 20:12

Satpal