Duplicating table rows dynamically

For some days I was looking for a JavaScript solution for duplicating table rows. I know it is simple. But I have made a function which does this very easily. I have tested this code with IE 6.0 and FireFox 2+ browsers.

Here is the JavaScript function:

/**
* This function duplicates a given row
* Author: Mohammad Sajjad Hossain
* Email: info @t sajjadhossain.com, msh134 @t gmail.com
*
* @param targetTableId - ID of the target table
* @param targetRowIndex - index of the row which to be duplicated
* @return void
*/
function duplicateRow(targetTableId, targetRowIndex)
{
     if(targetRowIndex == undefined)
     {
          targetRowIndex = 0;
     }
 
     var targetTable = document.getElementById(targetTableId);
     var tableBody = targetTable.tBodies[0];
     var targetRow = tableBody.getElementsByTagName("tr")[targetRowIndex];
     var newRow = targetRow.cloneNode(true);
     tableBody.appendChild(newRow);
}

Example Code:

<script language="javascript">
     function duplicateRow(targetTableId, targetRowIndex)
     {
          if(targetRowIndex == undefined)
          {
               targetRowIndex = 0;
          }
 
          var targetTable = document.getElementById(targetTableId);
          var tableBody = targetTable.tBodies[0];
          var targetRow = tableBody.getElementsByTagName("tr")[targetRowIndex];
          var newRow = targetRow.cloneNode(true);
          tableBody.appendChild(newRow);
     }
</script>
<table width="500" cellspacing="0" cellpadding="0" id="tblDuplicate" border="1">
     <tr>
          <th>Col1</th>
          <th>Col2</th>
          <th>Col3</th>
          <th>Col4</th>
     </tr>
     <tr>
          <td align="center">row</td>
          <td align="center">row</td>
          <td align="center">row</td>
          <td align="center">row</td>
     </tr>
</table>
<input type="button" value="Duplicate Row" onclick="duplicateRow('tblDuplicate', 1)" />
Share

1 Comment

  • By Arafat Rahman, January 6, 2008 @ 12:33 pm

    Thanks for your effort.
    I had a solution but I lost the code :(.

Other Links to this Post

RSS feed for comments on this post. TrackBack URI

Leave a comment

blog