Question

I have two functions in Javascript shown below:

function Add(){

    $("#tbl tbody").append(
        "<tr>"+
        "<td><input type='text'/></td>"+
        "<td><input type='text'/></td>"+
        "<td><input type='text'/></td>"+
        "<td><button class=\"btn btnSave\"><i class=\"icon-ok\"></i></button><button class=\"btn btnDelete\"><i class=\"icon-remove\"></i></button></td>"+
        "</tr>"

    );

    $(".btnSave").bind("click", Save);      
    $(".btnDelete").bind("click", Delete);

};

and

function Delete(){ 
    var par = $(this).parent().parent(); 
    par.remove(); 
};

and finally these two lines after the functions:

$(".btnDelete").bind("click", Delete);
$("#btnAdd").bind("click", Add);

The function Add() adds a new row to the table with id tbl. The last column in a newly added row has two buttons btnSave and btnDelete. btnDelete is supposed to delete that particular row as is evident from the Delete() function. (I have not started to implement the 'save' function yet). But, whenever I click the 'Delete' button, nothing happens. Is there a problem with the code?

I am using bootstrap css for my UI.

Function Add() works properly by the way.

Edit: Here is a screen capture. The highlighted button cross is not working. Screen Capture

Was it helpful?

Solution

It's may caused by duplicate event binding, try this code :

function Add(){

    $("#tbl tbody").append(
        "<tr>"+
        "<td><input type='text'/></td>"+
        "<td><input type='text'/></td>"+
        "<td><input type='text'/></td>"+
        "<td><button class=\"btn btnSave\"><i class=\"icon-ok\"></i></button><button class=\"btn btnDelete\"><i class=\"icon-remove\"></i></button></td>"+
        "</tr>"

    );
};

// it will also be affected for new objects
$(document).on("click", ".btnSave", Save);
$(document).on("click", ".btnDelete", Delete);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top