How To Add Dynamic Rows in a Table with jQuery

In this tutorial, i will discuss how to create a number of rows dynamically with help of jquery, There are a lot of methods which is used to create dynamic rows but we will use clone() jquery method to replicate rows.

Checkout other tutorials of Dynamically Add/edit and Delete Using jQuery,

Jquery provides a clone() method which is used to create a clone of that entity.
In this post, we will create a button and after click of that button we will add 5 rows to the target table body.

How To Add Row Dynamically in Table using jQuery

Step 1: Created a button that will add 5 rows when you clicked.

<div style="float: right; padding-right: 10px; padding-bottom: 10px;"><a class="btn add-records" role="button" data-added="0"><i class="icon-plus-sign"></i>&nbsp;Add Five Rows</a></div>

Step 2: Create target table where the dynamically rows will append.

<form enctype="multipart/form-data">
	<div class="divBgWhite" align="center">
		<div style="float:right; padding-right:10px; padding-bottom:10px;">
			<a role="button" class="btn add-records" data-added="0"><i class="icon-plus-sign"></i>&nbsp;Add Five Rows</a>
		</div>
		<table width="100%" class="table table-bordered table-hover record-table" id="tbl_addedit">
			<thead>
				<tr>
					<th width="8%">#</th>
					<th width="100px">Number</th>
				</tr>
			</thead>
			<tbody id="EditPreCon">
				<tr class="item-pre-con">
					<td><span class="sn"><?php echo $i+1; ?></span>.</td>
					<td>test</td>
					<td>Phpflow.com</td>
				</tr>
				<tr id="empty-tr">
					<td colspan="4"><div align="center"><strong>No record found!</strong></div></td>
				</tr>
			</tbody>
		</table>           
	</div>
</form>
<div style="display:none;">
	<table id="AddPreCon">
		<tbody>
			<tr class="item-pre-con">
				<td><span class="sn"></span>.</td>
				<td>test</td>
				<td>phpflow.com</td>
			</tr>
		</tbody>
	</table>
</div>

Step 3: Create event for button and add functionality to create clone and add rows into tbody.

jQuery(document).delegate('a.add-records', 'click', function(e) {
     e.preventDefault();    
    var content = jQuery('#AddPreCon tr'),
        size = jQuery('#tbl_addedit &gt;tbody &gt;tr').length,
        element = null,		 
    for(var i = 0; i<5; i++){
       element = content.clone();
        element.appendTo('#EditPreCon');
        element.find('.sn').html(++size);
    }
});

Result:

clone-jquery

Leave a Reply

Your email address will not be published. Required fields are marked *