Friday, January 6, 2012 Adding a row to a table containing form fields using jQuery
The following example shows how to add a new row to a table containing form fields using jQuery.
Firstly, create a table and a button that will add the new table row when clicked.
Now add the following JavaScript to the bottom of your page before the closing BODY tag. I have commented the code to explain what's happening.
And that's it..! :)
Tags
Comments
Monday, February 13, 2012 Dave Kelly
Nice article.
I implemented something similar the other day, but I needed to add blank lines to a table, and used this:
$line = $('table tbody tr:first').html();
$('table tbody').append('<tr>').append($line).append('</tr>');
clone() takes values and even handlers which I didn't want, and I don't care about duplicate names as I will be reading and posting the table with jQuery, so I just copy the html and append it to the tbody. Sadly grabbing the html of a tr does not take the tr tags itself, which would have been nice.
Saturday, August 4, 2012 Jill Garland
Intersting that this works in IE but not in Firefox. Any fixes?
Monday, August 6, 2012 Simon Bingham
I've tested in IE9 and it works for me.
Friday, August 10, 2012 Andrew Low
Thanks for this! I'll give it a try. One other thing I'll probably need to do is be able to delete a row. I'll do a google search to find out how however I wouldn't mind if you can suggest a good way :)
Thank you!
Friday, October 19, 2012 Simon Kincaid
Awesome. Very useful cheers. I'm wondering how the var parts = this.id.match(/(\D+)(\d+)$/); bit works - is this regular expressions?
Friday, October 19, 2012 Simon Bingham
Hi Simon. Yes, that's correct.
Thursday, December 6, 2012 Anonymous Anonymous
// break the field name and it's number into two parts
var parts = this.id.match(/(\D+)(\d+)$/);
In code "this.id.match...." must be "this.name.match..."
Thank you, liked idea much.
Wednesday, December 12, 2012 Jason Hall
Thanks. This a near perfect example of what I was looking for. A few minor modifications to the regex and I had exactly what I needed.
Thursday, December 20, 2012 Marco Antonio C
Thanks. Although I was looking to add a new row with input fields, your example code is a great start. Good call on the annotations...very useful
Thursday, February 7, 2013 Adam Ayman
Thanks but how i can have a new empty row ? and how can disable add row when last row is empty ?
