How to call a function within a custom button action?
How to call a function within a custom button action?
Hi, I'm trying to call a helper function within a datatables custom button. I've added 2 buttons to the button panel. I'm just showing one button now. Elsewhere in my html file, I have this function called init. Right now, I'm just putting an alert to test, but I want to eventually have it invoke a the production of a highchart barplot based on the data present. I'm wondering how do I call an external function within this custom button action?
<script type="text/javascript">
function init() {
alert( 'Testing' );
}
</script>
<script>
$.fn.dataTable.ext.buttons.view = {
text: 'View Data',
action: function ( e, dt, node, config ) {
init(dt);
}
};
$.fn.dataTable.ext.buttons.design = {
text: 'Design',
action: function ( e, dt, node, config ) {
alert( 'The table has '+dt.rows({ selected: true }).data().length+' records' );
}
};
$(document).ready(function() {
$('#results').DataTable( {
columnDefs: [ {
orderable: false,
className: 'select-checkbox',
targets: 0,
},
],
select: {
style: 'multi',
selector: 'td:first-child'
},
dom: 'Bfrtip',
buttons: [
'selectAll','selectNone','copy', 'csv', 'excel', 'view', 'design'
]
} );
} );
</script>
This question has an accepted answers - jump to answer
Answers
We're happy to take a look, but as per the forum rules, please link to a test case - a test case that replicates the issue will ensure you'll get a quick and accurate response. Information on how to create a test case (if you aren't able to link to the page you are working on) is available here.
Cheers,
Colin
Thanks Colin! I'm quite new to this. Here is my link on datatables:
http://live.datatables.net/butocake/1/
As mentioned, this is specifically trying to call a function within the action of the new view data button I had put in
Your test case wasn't setup quite right. jquery.js needs to load before datatables.js. Moved the CSS into the
head
portion of the page.I updated it to call the init function. I changed the init function to use console.log instead of alert. Alerts don't work unless you use the Live Preview option - I'm too lazy to go back and forth to the edit mode :-)
You can pass the
dt
parameter to the init() function for it to work. Alternatively you can use the instructions in the API docs to access the API from within any function without the need to pass a parameter. You already had this so I uncommented it.http://live.datatables.net/butocake/2/edit
Kevin
Thanks Kevin! This worked. And it's been so much easier to use the datatables test case for troubleshooting