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

后端 未结 3 1279
广开言路
广开言路 2020-12-28 20:01

I have the following:

<         
相关标签:
3条回答
  • 2020-12-28 20:39

    Give an id to your table, suppose my_table and an id to the anchor a suppose my_button then try the below:

    Your modified code:

    <table id="my_table">
    <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>
    </table>
    <a id="my_button" href='#'>Add Author</a>
    

    And add the below script after including the jquery library in your page.

    $(document).ready(function()
    {
      new_row="<tr><td><input type='text' name='first_name2' /></td><td><input type='text' name='last_name2'</td></tr>";
      $("#my_button").click(function()
      {    
        $("#my_table").append(new_row);
        return false;
    
      }
    }
    
    0 讨论(0)
  • 2020-12-28 20:44

    Check it out here.

    You'll probably want to increase the number in the name attributes in each iteration.

    0 讨论(0)
  • 2020-12-28 20:50

    Firstly, correct your HTML as:

    <table class="authors-list">
        <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>
    </table>
    <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:

    jQuery(function(){
        var counter = 1;
        jQuery('a.add-author').click(function(event){
            event.preventDefault();
    
            var newRow = jQuery('<tr><td><input type="text" name="first_name' +
                counter + '"/></td><td><input type="text" name="last_name' +
                counter + '"/></td></tr>');
                counter++;
            jQuery('table.authors-list').append(newRow);
    
        });
    });
    

    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.

    0 讨论(0)
提交回复
热议问题
author\'s first nameauthor\'s last name