TheDrunkenEpic - Drunken Ramblings of a Code Monkey
« Back to blog

jQuery: Add another row to a table ...

Here's another quick trick I just learned. We were attempting to allow a user to add more records to an existing form within our updated CRM. This form was represented as a row of a table. Rather than using JavaScript to manually build a new row to display, I did a bit of digging and found the clone() function of jQuery.

Say, we have a table with id of table#image-uploads that basically contains a minature upload form field (with other options) for images. In the last column of this upload form there is an 'add another' link:

add another

Clicking on the link invokes the following JavaScript function:

function addTableRow(table)
{
    $(table).append($(table + ' tr:last').clone());

    return true;
}

First, we pass the identifier to function addTableRow(table). The identifier, in this case, would be #image-uploads. You could also use classnames, ie .table-foo.

We then, using #image-uploads tr:last, take the last row of this table and clone(), or copy, it.

Finally, we just take the contents of the copied table row and then append() the data back onto the table.

There, now they can click that link and add as many extra form fields as they need for their images!

Neat trick, eh? I <3 jQuery. Really, I do!

Loading mentions Retweet

Comments (0)

Leave a comment...

 
To leave a comment on this posterous, please login by clicking one of the following.
Posterous-login     twitter