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

Hi, I'm Eftakhairul Islam, a passionate Software Engineer, Hacker and Open Source Enthusiast. I enjoy writing about technical things, work in a couple of startup as a technical advisor and in my spare time, I contribute a lot of open source projects.

 

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

  1. Hi!
    Thank you! Thank you! Thank you!

    The demo link is not working…!

    It is a good tutorial/article.

    Thank you!

  2. 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…

  3. Hi
    But it does not work with jquery mobile 1.3.2
    Any idea how to migrate to the new version?
    Many thanks
    Thomas

Leave a Reply to Hindujhan Cancel reply

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

 

This site uses Akismet to reduce spam. Learn how your comment data is processed.

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