Simon Suh Simon Suh - 1 year ago 117
HTML Question

How do I add an extra html table row upon button click using jQuery?

I have the following

<tr><td>author's first name</td><td>author's last name</td></tr>
<tr><td><input type='text' name='first_name' /></td><td><input type='text' name='last_name' /></td></tr>
<a href='' onclick='return false;'>Add Author</a>

and each time I click the link tag to 'add author', I want to create an extra table row like the following:

<tr><td><input type='text' name='first_name2' /></td><td><input type='text' name='last_name2'</td></tr>

I looked at .append() and I'm not sure exactly how to use it for my situation. And I'd like to be able to add infinite amount of new table rows. How do I do this?

Answer Source

Firstly, correct your HTML as:

<table class="authors-list">
        <td>author's first name</td><td>author's last name</td>
            <input type="text" name="first_name" />
            <input type="text" name="last_name" />
<a href="#" title="" class="add-author">Add Author</a>

(I have added indents only for visibility) and do not use inline JavaScript. Plus, be consistent, preferably use " (double quotes) for HTML attributes, ' (single quotes) for JavaScript strings.

Second, do something like that:

    var counter = 1;

        var newRow = jQuery('<tr><td><input type="text" name="first_name' +
            counter + '"/></td><td><input type="text" name="last_name' +
            counter + '"/></td></tr>');


It will add a row to the table with each click on the link having class add-author (just to be sure no other link is influented), incrementing number at the end of the name of every inserted field's name by 1. The row will be inserted at the end of the table having class authors-list (same reason as with class for a link). See this jsfiddle as a proof.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download