Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript - jquery DataTable append button to row + click event

its possible to attach click event when datatable is building the rows?, with out calling external global function and finding the closes tr and getting DATA object?.

$('#example').DataTable({
     columns : [{
        title   : 'msg',
        sClass  : 'col-sm-2',
        render  : function(data, type, row){
            var b = $('<button>the button</button>').click(function(){
                alert(row.msg);
            })
            return b;
        }
     }],
     ajax:{
        type : 'POST',
        url  : 'foo.php',
     }
});

i know the above example dosnt work, cos render function must return string, it just an example for what i need.

  • create an element.
  • attach click function passing 'row' object, with out calling global function.
like image 866
9879800 Avatar asked Sep 12 '25 18:09

9879800


1 Answers

Short answer, no you can't. I see you don't want to, but I would use a class and event delegation, like this:

var myDataTable=$('#example').DataTable({  // note the stored reference to the dataTable
     columns : [{
        title   : 'msg',
        sClass  : 'col-sm-2',
        render  : function(data, type, row){ 
            return '<button class="some-class">the button</button>';
        }
     }],
     ajax:{
        type : 'POST',
        url  : 'foo.php',
     }
});


$(document).on('click', '.some-class', function(){ 
        var $btn=$(this);
        var $tr=$btn.closest('tr');
        var dataTableRow=myDataTable.row($tr[0]); // get the DT row so we can use the API on it
        var rowData=dataTableRow.data();
        console.log(rowData.msg);
});

Technically you could use the rowCallback function to attach the handler after each row is rendered, but you'd have to use .find() or similar to get back to the button and the approach outlined above is far cleaner IMHO.

like image 62
Wesley Smith Avatar answered Sep 14 '25 09:09

Wesley Smith