1

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

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
kb_14
  • 267
  • 1
  • 6
  • 18

1 Answers1

5

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);
aimadnet
  • 440
  • 4
  • 12
  • Still not working!I have added: `$(document).on("click", "#btnAdd", Add);` also. Is it a problem because I have used a separate javascript file for the functions and the html code is in a different file? – kb_14 Apr 25 '14 at 22:15
  • It would be better to do the binding from `#tbl tbody` rather than `document`; that way the `btnSave` and `btnDelete` classes can be reused in other contexts. – ebohlman Apr 25 '14 at 22:17
  • yes you need to turn all your functions to be global, for example for Delete function => window.Delete = Delete ... – aimadnet Apr 25 '14 at 22:18
  • @aimadnet I made the functions global by doing this: `window.Delete = function(){....}` , but it is not working! Is there something that I am missing? – kb_14 Apr 25 '14 at 22:31
  • 1
    You've checked your console if there is a js error after you clicked the button? You can use Firebug for that. – aimadnet Apr 25 '14 at 22:35