We need to dynamically add rows to a table when the user clicks on an add button (this user event may also trigger an Ajax call to the server). This is an existing app that uses the <table>, <tr> and <td> tags for the table.

How can we achieve it using JavaScript and let the app be cross browser compatible.

  • Questioned edited, converted brackets to html entities so they appear in question. Edward Williams over 7 years ago

2 answers

danwellman 5600
1
point

simple; something like the following should suffice:

//click handler for button
$("#buttonid").click(function() {

  //create new table row
  var newRow = $("<tr>");

  //create same number of td's as last row of the table
  $.each($("#tableid").children(":last").children(), function() {
    $("<td>").addClass("any-class-name-you-want").appendTo(newRow);
  });

  //append new row to table
  newRow.appendTo("#tableid");

  //make an AJAX call, or do whatever else you want here
});

That should do what you need, although it could probably be optimised ;)

Answered over 7 years ago by danwellman
elena 56
0
points

Simple answer: Add A Row (Copy and paste 1.4K of js)

More complicated: Add, Remove, Submit Row (Looks pretty solid on cross-browser front.)

Answered over 7 years ago by elena