Reputation: 1170
the code below add and remove table row with the help of Jquery the add function works fine but the remove only work if I remove the first row
<table>
<tr>
<td><button type="button" class="removebutton" title="Remove this row">X</button>
</td>
<td><input type="text" id="txtTitle" name="txtTitle"></td>
<td><input type="text" id="txtLink" name="txtLink"></td>
</tr>
</table>
<button id ="addbutton">Add Row</button>
and the script
var i = 1;
$("#addbutton").click(function() {
$("table tr:first").clone().find("input").each(function() {
$(this).val('').attr({
'id': function(_, id) {return id + i },
'name': function(_, name) { return name + i },
'value': ''
});
}).end().appendTo("table");
i++;
});
$('button.removebutton').on('click',function() {
alert("aa");
$(this).closest( 'tr').remove();
return false;
});
can anyone give me the explanation why I can only remove the first row ? thank so much
Upvotes: 20
Views: 103310
Reputation: 1077
I know this is old but I've used a function similar to this...
deleteRow: function (ctrl) {
//remove the row from the table
$(ctrl).closest('tr').remove();
}
... with markup like this ...
<tr>
<td><span id="spDeleteRow" onclick="deleteRow(this)">X</td>
<td> blah blah </td>
</tr>
...and it works fine
Upvotes: 0
Reputation: 4076
You should use Event Delegation, because of the fact that you are creating dynamic rows.
$(document).on('click','button.removebutton', function() {
alert("aa");
$(this).closest('tr').remove();
return false;
});
Upvotes: 5
Reputation: 484
$(document.body).on('click', 'buttontrash', function () { // <-- changes
alert("aa");
/$(this).closest('tr').remove();
return false;
});
This works perfectly, take not of document.body
Upvotes: -1
Reputation: 13425
A simple solution is encapsulate code of button event in a function, and call it when you add TRs too:
var i = 1;
$("#addbutton").click(function() {
$("table tr:first").clone().find("input").each(function() {
$(this).val('').attr({
'id': function(_, id) {return id + i },
'name': function(_, name) { return name + i },
'value': ''
});
}).end().appendTo("table");
i++;
applyRemoveEvent();
});
function applyRemoveEvent(){
$('button.removebutton').on('click',function() {
alert("aa");
$(this).closest( 'tr').remove();
return false;
});
};
applyRemoveEvent();
Upvotes: 1
Reputation: 1760
When cloning, by default it will not clone the events. The added rows do not have an event handler attached to them. If you call clone(true)
then it should handle them as well.
Upvotes: 3
Reputation: 61055
You need to use event delegation because those buttons don't exist on load:
http://jsfiddle.net/isherwood/Z7fG7/1/
$(document).on('click', 'button.removebutton', function () { // <-- changes
alert("aa");
$(this).closest('tr').remove();
return false;
});
Upvotes: 39