Reputation: 1606
Really simple: with jQuery I add a new TR
that has a delete button. But when delete button is clicked, nothing happens (should remove the newly created TR
). I can’t get it work. I’m almost certain it has something to do with this:
$('.delete-data').on('click touchstart', '.add-new', function() {
My code:
// if clicked on new button add new TR
$('.add-new').on('click touchstart', function() {
if ($(this).hasClass('company')) {
newTr('company');
} else {
newTr('user');
}
})
// adds new TR to table
function newTr(type) {
var table = $('table');
if (table.hasClass(type)) {
table.find('tbody').append(
'<tr contenteditable="true">
<td>New ' + type + ' name</td>
<td>License type</td>
<td>0</td>
<td>Expiry date</td>
<td>xYsqffSX3X4a</td>
<td class="delete-data" title="Delete this">×</td>
</tr>'
);
}
}
// deletes data from table
$('.delete-data').on('click touchstart', '.add-new', function() {
var parent = $(this).parent(),
label = parent.find("td:first").html(),
r = window.confirm("Permanently delete " + label + " and all its data?");
if (r == true)
parent.remove();
})
Any ideas? Thanks!
EDIT: Thanks to Barmar the solution is this one:
$('table').on('click touchstart', '.delete-data', function() {
Upvotes: 0
Views: 919
Reputation: 934
It's my first post on stackoverflow ;) Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to. Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, you can use delegated events to avoid the need to frequently attach and remove event handlers. So, about you example:
$('.example_table').on('click touchstart', 'td.delete-data', function() {})
Upvotes: 1
Reputation: 780724
Try:
$("table").on('click touchstart', '.delete-data', function() {
...
}
When you use event delegation, you must bind to a static element ($("table")
in this case), and give a selector for the dynamic element (.delete-data
) in the arguments.
Upvotes: 1