How to add a new row to html table on press of a button using jQuery

Scenario

There is an HTML table on a web page which shows a details of students in a class. In order to add a new student record to this table, there should be a button. When this button is clicked, a new row should be inserted at the end of the table. This can be done using jQuery. Below content shows how !!!

There are two approaches to do this:

Method 1 : Count the number of columns in the table. Iterate over these columns and create html for the new row. Code for this would be:

 function addNewRow() {
   // fetch last row and calculate the length of columns in it
   var totalColumns = $("#myTable tbody tr:last td").length;
   // initialize table start code
   var rowHtml='<tr>';
   // new row will have the same number of columns as last row
   for(var i = 0; i < totalColumns; i++){
     // create table columns
     var columnHtml = '<td></td>'; 
     // append table columns to row rowHtml = rowHtml + columnHtml; }    
     //append end tag of table row 
     rowHtml = rowHtml + '</tr>'; 
     //add row to table end 
     $("#myTable").append(rowHtml); 
}


Details :

  1. First we determine the number of columns in the last row of the table using length property.
  2. Initialize html code for start of a table row i.e., ‘<tr>’.
  3. Then create a loop with maximum value as this count and create table column html inside this loop i.e., sequence of ‘<td>’ tags. Merge table column code to table start code after every iteration.
  4. After the loop append row end tag (<tr>) to the above html code.
  5. Finally this html code is appended to table.

Method 2 : Make a copy of last or first row and append it to table.

 function addNewRow() {
   // make a copy of an existing row. We choose the last row of table
   var rowToAdd = $("#myTable tbody tr:last").clone();
   // empty cells of this row
   $(rowToAdd).find('td').each(function(){
      $(this).text('');
   });
   //add it to table
   $("#myTable tbody").append(rowToAdd);
}


Details :

  1. Make a copy of the last row of table. This is done using clone function. You can also clone the first row of the table.
  2. Iterate over the cells of cloned row and make them empty. This is done so that the added row is empty. Otherwise both rows will be same.
  3. Finally append this to table using jQuery’s append function.

Reading this line…Cool!!! How can others read this. Simple!!! If you share.