Francois Francois - 3 months ago 24
jQuery Question

Duplicate row in my table

I have a problem in duplicating a row into my table.

I want to duplicate my following table row:

<table class="table table-bordered table-striped">
<tr>
<th>Service</th>
<th>Début</th>
<th>Fin</th>
<th>État</th>
<th>&nbsp;</th>
</tr>
<tr class="tr_clone">
<td>&nbsp;</td>
<td><span class="controls">
<input class="placeholder span2 datepicker" type="text" value="" data-date-format="yyyy-mm-dd">
</span></td>
<td><span class="controls">
<input class="placeholder span2 datepicker" type="text" value="" data-date-format="yyyy-mm-dd">
</span></td>
<td>&nbsp;</td>
<td>&nbsp;</td>
</tr>
</table>
<p><a href="#" class="tr_clone_add">Ajouter une ligne</a></p>


With this Js code:

$(".tr_clone_add").live('click', function() {
var $tr = $('table').closest('.tr_clone');
var $clone = $tr.clone();
$clone.find(':text').val('');
$tr.after($clone);
});


But it does not work.

Could you please help me with this case ?

Thanks.

Answer

Use this

  $(function(){
$(".tr_clone_add").live('click', function() {
    var $tr    = $('table').find('.tr_clone').first();
    var $clone = $tr.clone();
    $clone.find(':text').val('');
    $tr.after($clone);
});
});

You dont need

 var $tr    = $('table').closest('.tr_clone');

EDit: If want to add duplicate row in each table then try this

     $(function(){
    $(".tr_clone_add").live('click', function() {
        $('table').each(function(i,v){
        var $tr    = $(this).find('.tr_clone').first();
        var $clone = $tr.clone();
        $clone.find(':text').val('');
        $tr.after($clone);
        })

    });
    });