Andy Andy - 27 days ago 9
HTML Question

.click function will only work inside a parent .click function and cannot be executed outside it

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:


  1. Table is loaded.

  2. 'Edit' button (with a class
    editBtn
    ) appears on each row.

  3. Clicking the 'Edit' button removes the class
    editBtn
    and adds a class
    saveBtn
    . 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?

Answer

It is not working because you are appending .savebtn after click event is bind. you have to use document on click. this will 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
    $(document).on('click', '.saveBtn', function(){ 
        console.log('savebtn');
    });