I've been developing an application which allows table rows to be edited using jquery. The original post is here Targetting a <td> from it's parents <tr> with data-attributes using jquery
The flow of the application is:
- Table is loaded.
- 'Edit' button (with a class
editBtn
) appears on each row. - Clicking the 'Edit' button removes the class
editBtn
and adds a classsaveBtn
. The text is also changed from 'Edit' to 'Save'.
The intention is that when clicking the Save button I can do an ajax request.
However, I can only target the .saveBtn
being clicked if the jquery for it resides inside the original .click
function on .editBtn
. So for example, this works:
$('.editBtn').click(function() {
var $button = $(this).addClass('save').text('Save');
var $tr = $button.closest('tr');
var id = $tr.data('id');
var $td = $tr.find('td:first');
var $td2 = $tr.find('td:nth-child(2)');
$td.html('<input value="' + $td.text() + '" />');
$td2.html('<button class="btn btn-primary btn-success saveBtn">Save</button>');
$('.saveBtn').click(function() {
console.log('savebtn');
});
});
But this does not work:
$('.editBtn').click(function() {
var $button = $(this).addClass('save').text('Save');
var $tr = $button.closest('tr');
var id = $tr.data('id');
var $td = $tr.find('td:first');
var $td2 = $tr.find('td:nth-child(2)');
$td.html('<input value="' + $td.text() + '" />');
$td2.html('<button class="btn btn-primary btn-success saveBtn">Save</button>');
});
// Moved outside $('.editBtn').click
$('.saveBtn').click(function() {
console.log('savebtn');
});
Why is this?