kate_hudson kate_hudson - 7 months ago 39
Javascript Question

Cloning closest table row

I recently asked this question

Since then I have discovered that what I wanted to do wont work. This is because the table is generated by a for loop, with their id incrementing each time. As such, I needed to amend things so that it would add rows for the table it is supposed too. I have updated my fiddle to show an example with two table JSFiddle

Essentially, I now do this

$(function() {
$(".addCF").click(function(){
var clone = $(this).closest('tr').clone(true).insertAfter($(this).closest('tr'));
});
$("#customFields").on('click','.remCF',function(){
$(this).parent().parent().remove();
});
});


I can get the name and label of the cloned rows done myself using the previous examples. My main problem is that I do not want to clone the whole row. At the moment, it is cloning this

<tr>
<td><label class="subjectline" for="User1">User NOC M1</label></td>
<td id="slLabel">SL_A</td>
<td id="slInput"><input type="text" name="slOptions[User][NOC M1]" class="form-control" id="User1"></td>
<td><a class="addCF" href="javascript:void(0);">+ additional user</a></td>
</tr>


I need it to clone this but make the first td empty. Additionally, like the initial question, the last td should be a close button

<a href="javascript:void(0);" class="remCF">Remove</a>


Is it possible to do this?

Thanks

Answer

From the cloned tr,

  1. empty its first-child(td) 's content.
  2. Set its last-child(td) 's html as the close element's html,

$(function() {
    $(".addCF").click(function(){
       var clone = $(this).closest('tr').clone(true);
       $("td:first-child", clone).empty();
       $("td:last-child", clone).html('<a href="javascript:void(0);" class="remCF">Remove</a>');
       clone.insertAfter( $(this).closest('tr'));
    });
    $("table.table").on('click','.remCF',function(){
        $(this).parent().parent().remove();
    });
});

DEMO