JavaScript - jquery DataTable append button to row + click event -
its possible attach click event when datatable building rows?, out calling external global function , finding closes tr , 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 above example dosnt work, cos render function must return string, example need.
- create element.
- attach click function passing 'row' object, out calling global function.
short answer, no can't. see don't want to, use class , event delegation, this:
var mydatatable=$('#example').datatable({ // note stored reference 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]); // dt row can use api on var rowdata=datatablerow.data(); console.log(rowdata.msg); });
technically use rowcallback
function attach handler after each row rendered, you'd have use .find()
or similar button , approach outlined above far cleaner imho.
Comments
Post a Comment