Friday, February 24, 2017

Dynamically add/remove table rows using jquery

While developing complex DOM structures, many time we come across the designs where we may need to control the height of the HTML table dynamically. In many situations, the requirement is to let users manage the number of table rows. This is really a simple code and can be easily written using JavaScript and jQuery.

Before we move and check the code I want to highlight that one must know the use of jQuery methods such as "append()", "close()" & "remove()". If you know the purpose and working of these methods then this job will be a piece of cake for you.

Click to view Demo

Step 1. Copy below HTML markup for table
<table id="table">
    <tr valign="top" >
      <th scope="row"><label>Label</label></th>
        <input type="text" id="field1" />  
        <input type="text" id="field2" />  
        <a href="javascript:void(0);" class="add">Add</a>    <a href="javascript:void(0);" class="remove">Remove</a>
Note that you will have to keep one row in this table which needs to be cloned dynamically. We can also keep empty table but in that case, we will need to create a DOM object using jQuery. Let's first understand the logic of dynamically adding the rows and later on you can remove first row as well.

Step 2. jQuery code to dynamically add/remove rows of the table
    rowObj = $("#table tr:first").clone();
    $( "#table" ).append(rowObj);

I have used CSS selector rule "#table tr:first" to select the first row of the table. I am using .clone() method on that selector to make a copy of it and saved it in rowObj variable. This object is nothing but a DOM element which we can append to any parent. So next job is to just append the cloned DOM element to the table using "append()" method. Similarly I have used remove() method to dynamically remove the table row.

No comments:

Post a Comment