TheDrunkenEpic

Hello, I'm Wilhelm, a PHP developer, and this is my little corner of the internet where I can discuss things that interest me and, hopefully, you too. :-)


Currently Reading:

1Oct 2008

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:

<a href="#" onclick="addTableRow('#image-uploads'); return false;" title="Add another upload field">add another</a>

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!


Your Commentary:

Another very cool trick! NICE!

Sean Cannon spoke the truth on October 1st at 10:58 am #

That's 'cause jQuery is teh rox. ;)

But yea, consistent posts like this, maybe a new site design, and I see no reason you can't be one of those famous pro-tech-blogger things. You know, like the one's over at A List Apart. lol :P

You're so helpful. *hearts*

Lorren Biffin spoke the truth on October 1st at 1:40 pm #

Yeah, well, a complete redesign and repurposing of this site has been a plan of mine for some time now. I was going to move the support forums for MyTopix over here, so the community and this site are all in one spot. This will also be the initial release hub for Cogsworth, so things are going to change anyway pretty soon.

I'm pretty stoked!

Glad you both liked the article. ;)

Wilhelm Murdoch spoke the truth on October 1st at 6:43 pm #

TrackBack: http://www.thedrunkenepic.com/home/articles/trackback/117/

Leave a Comment: