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 about 10 years ago

2 answers

danwellman 5600

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() {

  //append new row to table

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

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

Answered about 10 years ago by danwellman
elena 56

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 about 10 years ago by elena