Dynamically add and delete html table row on user click using jQuery

This is very simple javascript function using jQuery library for deleting or adding html table row on user click. Basically, I had to write this functionality for one of my client’s  projects. There was a table with some input fields in each row what user can manipulate by inserting data, adding or deleting those rows.  So, I made like following picture.

Code is really simple.  Consider we have following HTML table with any style sheet.

<table id="options-table">
	<tbody>
		<tr>
			<td>Input-Box-One</td>
			<td>Input-Box-Two</td>
			<td></td>
		</tr>
		<tr>
			<td><input type="text" name="input_box_one[]" /></td>
			<td><input type="text" name="input_box_one[]" /></td>
			<td><input class="del" type="button" value="Delete" /></td>
		</tr>
		<tr>
			<td><input type="text" name="input_box_one[]" /></td>
			<td><input type="text" name="input_box_one[]" /></td>
			<td><input class="add" type="button" value="Add More" /></td>
		</tr>
	</tbody>
</table>

If we want more rows then we have to add new row to the table.

$('.add').live('click',function(){
	$(this).val('Delete');
	$(this).attr('class','del');

	var appendTxt = "<tr><td><input type="text" name="input_box_one[]" /></td><td><input type="text" name="input_box_two[]" /></td><td><input class="add" type="button" value="Add More" /></td></tr>";
	$("tr:last").after(appendTxt);
});

Delete a row from Table.

$('.del').live('click',function(){
	$(this).parent().parent().remove();
});

You can even take look at demo or download sourcecode.

 

Eftakhairul Islam

Eftakhairul Islam is a passionate Software Engineer, Tech Blogger and Open Source Enthusiast.

 

15 thoughts on “Dynamically add and delete html table row on user click using jQuery

  1. I am a hobistic web designer but still in my early stage of this so i must say Thanks a lot for this very simple and useful article… i was really looking for this…

Leave a Reply

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

 

Read previous post:
Change the Mirror Repository of Ubuntu

Recently, I installed the new version of Ubuntu: 11.10 (Oneiric Ocelot) in my desktop to take its taste. But I...

Close