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

Happy New Year 2008

Happy New Year 2008

Share

MSH Test Emperor v1.0 – A MCQ Exam Engine for SCJP

MSH Test Emperor, designed and developed by myself. I think it will be helpful to the peoples who are willing to attend the Sun Certified Programmer for Java exam. The exam engine contains a built in SCJP mock exam which serves 61 questions, randomly selected from a question set of 255 questions.This engine is developed totally with Java. After passing the SCJP exam, I have developed this engine.

More >>

Share
blog