Adding rows dynamically to a table using jQuery - Part 2

Continuation of series where we discuss Jquery APIs and the template for dynamic rows

Adding rows dynamically to a table using jQuery - Part 2

In this post we shall cover how to add a new row to a table. This post would be a continuation of Part I.

To dynamically add a row to a table, I would be using the append functionality of jQuery. We can use either the

CLONE method (https://api.jquery.com/clone/)

Create a copy of the set of matched elements.

or APPEND method (https://api.jquery.com/append/)

Insert content, specified by the parameter, to the end of each element in the set of matched elements.

I prefer the append method because we got more control on the generation of the element ids/names. In the clone method, the element ids are also copied & by default the events associated are not copied (Using withDataAndEvents parameter we can change this default behaviour).

The HTML which will be appended to the table body –

var newItem = $("
<tr> 
 <td> 
  <input type='text' class='classTextbox' jsonsyntax='EmpName' 
  id='txtEmpName" + index + "' name='txtEmpName" + index + "'/> 
 </td>
 <td>
  <input type='text' jsonsyntax='City' class='classTextbox' 
  id='txtCity" + index + "' name='txtCity" + index + "' /> 
 </td>
 <td>
  <input type='text' class='classTextbox' jsonsyntax='Dept' 
  id='txtDept" + index + "' name='txtDept" + index + "' /> 
 </td>
 <td>
  <input type='text' jsonsyntax='Age' class='classTextbox' 
  id='txtAge" + index + "' name='txtAge" + index + "' /> 
 </td>
 <td>
  <img id='btnPlus" + index + "' src='../Images/add.png' class='classImage' 
  title='" + $strAdd + "' onclick='AddClicked();'/> 
  <img class='classImage' id='btnMinus" + index + "' title='" + $strDelete + "' 
  src='../Images/delete.png' onClick='RemoveRow(this);'/>
 </td>
</tr>");

All the new rows added to the table would contain unique ids/names. The dynamically added controls have an index appended to them.

In the next post I shall explain the functionality of AddClicked() and RemoveRow() funtions. Also I shall explain how the jsonsyntax tag would help us in retrieving multiple control/element data for pre-processing; before its sent to the server.