Insert new row with button - Buttons jQuery on-click fails

Insert new row with button - Buttons jQuery on-click fails

jhylandjhyland Posts: 3Questions: 2Answers: 0

So I have a DataTable on a page with a button that will insert a new row when clicked. One of the columns contains a link that should simply alert something, however... it doesnt do anything at all.

Heres the jQuery

$(document).ready(function() {

    var clients_table = $('#add_clients').DataTable();

    $('#addRow').on( 'click', function () {
        
        clients_table.row.add( [
            '<input type="text" class="hostname" name="hostname[]">',
            '<input type="text" class="IP" name="ip[]">',
            '<select name="deploy_method[]"><option value="YUM" selected="selected">Yum</option><option value="cfengine">CFengine</option></select>',
            '<a href="#" class="deleteRow">Remove</a>'
        ] ).draw();
    } );
    
    $('.deleteRow').on( 'click', function () {
        alert('test');
    });
} );

Answers

  • ignignoktignignokt Posts: 146Questions: 4Answers: 39
    edited October 2014

    This is more of a jQuery question than a DataTables question. But, try changing your click function to:

    $(document).on('click','.deleteRow',function(){
        alert('test');
    });
    
  • jhylandjhyland Posts: 3Questions: 2Answers: 0

    That works fine, I guess its the document.ready? Maybe looks at the DOM values and will only take action on whats found when the documents initially loaded and ready.

    Thanks!

  • ignignoktignignokt Posts: 146Questions: 4Answers: 39
    edited October 2014

    I'm more of a PHP guy, but I believe it is something to do with the click function you wrote is bound to elements that already exist. So anything loaded afterwards won't have that bound to it.

  • allanallan Posts: 63,386Questions: 1Answers: 10,449 Site admin

    Correct - you were using a static event handler before - but @ignignokt's suggestion was to use a delegated event handler. See the top FAQ.

    Allan

This discussion has been closed.