Reputation: 2492
I generate table with jquery and I generate button and put it in each row of this table I want to set event for that buttons that whenever each of them clicked remove that particular row which that button is in there
here is my code:
$("#table_sample").append("<tr>" +
"<td>" + value1 + "</td>" +
"<td>" + value2 + "</td>" +
"<td>" + value3 + "</td>" +
"<td>" + "<button type='button' class='col-sm-7 btn btn-danger pull-right'>delete</button> " +
"</td></tr>");
Is there any way that can set event for each of them that can delete their rows?
Upvotes: 0
Views: 113
Reputation: 2981
You can try something like this:
$("#myButton").click(function ()
{
var test = $('<button/>',
{
text: 'Test',
click: function () { alert('hi'); }
});
var parent = $('<tr><td></td></tr>').children().append(test).end();
$("#addNodeTable tr:last").before(parent);
});
Or,
$("#myButton").click(function ()
{
var test = $('<button/>',
{
text: 'Test',
click: function () { alert('hi'); }
}).wrap('<tr><td></td></tr>').closest('tr');
$("#addNodeTable tr:last").before(test);
});
Upvotes: 0
Reputation: 43156
You can use closest() to target the parent row.
$("#table_sample").on('click','.btn-danger',function(){
$(this).closest('tr').remove();
});
Note that you also neeed to delegate the event on dynamically created elements using the .on() method (Assuming you're using jQuery version 1.71 or later)
Upvotes: 1
Reputation: 67207
Try to use .closest()
to grab the parent row of the clicked button,
$('#table_sample').on('click','tr td :button:contains(delete)',function(e){
$(this).closest('tr').remove();
});
And note that we have used event delegation here, since those buttons are being created at the runtime.
Special note: I have used the :contains()
selector here, because I don't know the exact identity of those buttons, you must have some common identifiable class to them, use that instead.
Upvotes: 1