2

I cloned a row from a table, I want to remove the last cloned row by clicking the delete button.

Here is my script

$("#btnAddMoreUser").on("click",function(){
    var newClass='newClass';
    var $tableBody = $('#tblAddUser').find("tbody"),
        $trLast = $tableBody.find("tr:last"),
        $trNew = $trLast.clone().addClass(newClass);
        $trLast.after($trNew);
 });   

$(".tr_clone_remove").on("click",function(){ //Once remove button is clicked
    $(".newClass:last").remove(); //Remove field html
    x--; //Decrement field counter
}); 

Below is my fiddle

https://jsfiddle.net/7nr3gc2t/

Middlerange
  • 115
  • 1
  • 11
  • $(document).on("click", ".tr_clone_remove", function (e) { //user click on remove e.preventDefault(); $(".newClass:first").remove(); }); it works – Sathish Thangaraj Aug 29 '18 at 09:39

1 Answers1

0

You need to use event delegation for attaching events to dynamically added elements.

Also your code is removing the first row in matched set every time. You should use closest to traverse to closest row and then remove it:

$('#tblAddUser').on("click",".tr_clone_remove",function(){ //Once remove button is clicked
   $(this).closest(".newClass").remove(); //Remove field html
  x--; //Decrement field counter
}); 

Working Demo

Milind Anantwar
  • 81,290
  • 25
  • 94
  • 125