简体   繁体   中英

jQuery Adding New Table Row Not at the End of the Table

I have an HTML Table and would like to allow the user to click a button to add a new Row, but the new Row will not be added at the end of the table but rather after the last row of input fields.

I've setup a sample JSFiddle at:

http://jsfiddle.net/n7Gup/2/

I have a New Row button but it's not cloning the last row of inputs (ie the row where the New Row button is). I need to modify this so that it will insert a new row after the last of these input rows.

Here's the script which I found from an online tutorial:

$(document).ready(function($)
{
  // trigger event when button is clicked
  $("#button2").click(function()
  {
    // add new row to table using addTableRow function
    addTableRow($("#nextYear"));

    // prevent button redirecting to new page
    return false;
  });

  // function to add a new row to a table by cloning the last row and
  // incrementing the name and id values by 1 to make them unique
  function addTableRow(table)
  {
    // clone the last row in the table
    var $tr = $(table).find("tbody tr:last").clone();

    // get the name attribute for the input and select fields
    $tr.find("input,select").attr("name", function()
    {
      // break the field name and it's number into two parts
      var parts = this.id.match(/(\D+)(\d+)$/);

      // create a unique name for the new field by incrementing
      // the number for the previous field by 1
      return parts[1] + ++parts[2];
    // repeat for id attributes
    }).attr("id", function()
    {
      var parts = this.id.match(/(\D+)(\d+)$/);
      return parts[1] + ++parts[2];
    });

    // append the new row to the table
    $(table).find("tbody tr:last").after($tr);
  };
});

The new row that is created can have all the input fields empty as the user will start again. Also is there a way to have the New Row button only appear once, and that will always be at the last row of activity inputs. For example initially there will only be one row, but if you click the New Row button a 2nd row will be created below the initial row and the New Row button will now only appear on this newly created row.

Appreciate any help - I'm new to Javascript.

Here is a solution

http://jsfiddle.net/7vuZf/3/

Basically you simply pass the reference to the the button clicked and work out your positioning in the table from there - save the reference to the current last row (using closest(), clone it (with events), remove the new row button in the original (you probably need to replace it with a delete button), and insert the clone after the original.

Also now you probably do not need a reference to the table object passed to your click handler (I left it in the code though).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM