I have a dynamic table where users can add and delete rows. When the user clicks a button to add a row, I want to insert into the DOM a stored jQuery object which is a copy of the initial table row .baseRow. Within this row, I also want to have a delegated click event that stays alive for future added rows.
However, two issues are presenting themselves with my current implementation (tested in Chrome/IE). The first is that the click handler breaks after the first event is fired. I am able to solve this by chaining .html() after .clone(), but when I do that the clone is inexplicably stripped of the parent tr element and is reduced to just the children elements.
See this js fiddle for an example of the issue, or below for a sample of the code:
JS
$('document').ready(function(){
var $baseRow = $('.baseRow').clone(true,true);
$('table').delegate('.addRow','click',function(){
$('tbody').append($baseRow);
});
});
HTML
<table>
<thead>
<tr>
<th>Add Row</th>
<th>Header 1</th>
<th>Header 2</th>
</tr>
</thead>
<tbody>
<tr class="baseRow">
<td class="addRow">+</td>
<td>Body 1</td>
<td>Body 2</td>
</tr>
</tbody>
</table>
You clone once, and append that cloned element over and over. Since there is only one clone, you won’t ever have more than two elements (original + clone). Instead, clone when clicked, so that the amount of clones equals the amount of clicks: http://jsfiddle.net/YxB9J/5/.