jQuery clone table row example

by Paul Leech

HTML

<table border='1' id='ct_blah'>
    <tr>
    <td>header</td>
    <td><input type='text' /></td>
    <td><input type="checkbox" id="chkbx01" /><label for="chkbx01">Set</label></td>
    </tr>
    <tr><td>mid</td><td><input type='text' /></td>
    <td><input type="checkbox" id="chkbx02" /><label for="chkbx02">Set</label></td>
    </tr>
    <tr><td>last</td><td><input type='text' /></td>
    <td><input type="checkbox" id="chkbx03" /><label for="chkbx03">Set</label></td>
    </tr>
    
    <tr class="ui-widget-header"><td><input value=" + " id="addRow" type='button' /><input id="removeRow" value=" - " type='button' /></td><td></td><td></td></tr>
    
</table>

CSS

table#ct_blah tr th, 
table#ct_blah tr td { 
  font-family:sans-serif; 
  text-align:center;
}

JavaScript

//$("table tr:not('ui-widget-header'):last").clone().appendTo('body');

$(":button #addRow").click(function(){
    var $lastRow = $("[id$=blah] tr:not('.ui-widget-header'):last"); //grab row before the last row
    var $newRow = $lastRow.clone(); //clone it
    $newRow.find(":text").val(""); //clear out textbox values    
    $lastRow.after($newRow); //add in the new row at the end
});
$(":button #removeRow").click(function(){
//   $(this).closest('tr').remove();
//  	return false;
    //var $lastRow = $("[id$=blah] tr:not('.ui-widget-header'):last"); //grab row before the last row
    //var $newRow = $lastRow.remove(); //clone it
    //$newRow.find(":text").val(""); //clear out textbox values    
    //$lastRow.after($newRow); //add in the new row at the end
});