Home  /  Questions  /  Question



50   50
Apr 09, 2013


Need example of jQuery adding rows to complex HTML tables

I have a series of pages with tables that may or may not have thead, tbody, and tfoot elements, like so: 
There are many tables, again with different configurations. 
<table>
    <thead>
       <th><td>First Name</td><td>Last Name</td></th>
    </thead> 
    <tfoot>
        <tr><td colspan="2">Constituents</td></tr>
    </tfoot>
    <tbody>
        <tr><td>Rakesh</td><td>Srinivasi</td></tr>
        <tr><td>Andy</td><td>Allison</td></tr>
    </tbody>
</table>
I need a general function that uses jQuery to append rows to any of these tables. 
Note, the new row should follow the last one, so in the example above following Andy Allison.

Any examples or example code appreciated.
 



1,364   100.0
Apr 17, 2013
There are various ways to do this in jQuery.  One quick thing you can try out is the below code.  But do work with it and tune this for your requirement..(I have just quickly typed this.. you may consider other approaches like individually creating TR/TD elements and adding it).

Assuming table has ID (you can change this)...

http://jsbin.com/emipuj/1/


H
ope this helps..
$(function () {
  $("#btnAdd").on("click", function (e) {
    $('#table1 tbody>tr:last').clone(true).insertAfter('#table1 tbody>tr:last');
    $('#table1 tbody>tr:last td').each(function (i,td) {
        $(td).text("some value");
    });
  });
});

 
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body>
  <table id="table1" border="1">
    <thead>
      
      <tr><th>First Name</th>
      <th>Last Name</th></tr>
    </thead> 
    <tfoot>
        <tr><td colspan="2">Constituents</td></tr>
    </tfoot>
    <tbody>
        <tr><td>Rakesh</td><td>Srinivasi</td></tr>
        <tr><td>Andy</td><td>Allison</td></tr>
    </tbody>
</table>
  
  <input type="button" value="Add Row" id="btnAdd"/>
</body>
</html>