Dofactory.com
Dofactory.com
 Back to list
Views:   16.3K
Replies:  1
Archived

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.
 
Sunil Patel, Apr 09, 2013
Reply 1
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>

 
Rajesh Pillai, Apr 17, 2013
thanks for your response , I want to create a custom menuhandler with composite pattern which will render menu to jquery menu on asp.net, Is it possible ,or if it is possible is there be a performance problem ?
Jan 25, 2012
Stay Inspired!
Join other developers and designers who have already signed up for our mailing list.
Terms     Privacy     Cookies       Do Not Sell       Licensing      
Made with    in Austin, Texas.  - vsn 44.0.0
© Data & Object Factory, LLC.