Custom buttons

Buttons own table manipulation modules can be exceptionally useful, but the true flexibility of Buttons can only be unlocked by providing custom buttons which address problems which are unique to the domain you are working in.

For example, consider a table of pupils in class registration. To mark absent pupils a single button could be used along with the Select extension to firstly select missing pupils and then update a database at a single click.

Another example is a button that will reload the data of a DataTable - which we will explore below.

The options of what a button can do are endless; it simply executes a Javascript function that you can define!

Required parameters

When you construct a Buttons instance, we've seen already how you can use an object to define each button. While you will typically extend a built in button this is not required.

In fact none of the parameters are actually required - however, you will almost always wish to provide text for the button and an action. After all, without either of these, the button's functionality is rather limited!

Define during initialisation

Let's expand upon the reload example given above. With an Ajax sourced DataTable (ajax) we can use the ajax.reload() method to reload the data from the server. A button that calls this method provides the end user with the ability to refresh the table's data and can be constructed like this:

$('#myTable').DataTable( {
    ajax: '/api/data'
    buttons: [
        {
            text: 'Reload',
            action: function ( e, dt, node, config ) {
                dt.ajax.reload();
            }
        }
    ]
} );

Note that the buttons.buttons.action function is passed four parameters. These parameters describe the event that triggered the action, the DataTable hosting the button and the button itself. A full description can be found in the reference documentation.

Custom button type

Defining a custom button, as above, can be very useful for single one-off buttons, but it is also possible to define a reusable button that is extendable in exactly the same way as the the pre-defined buttons. This can be done by attaching your button definition object to the $.fn.dataTable.ext.buttons object - the parameter name used is the name that will reference the button in the initialisation.

For the reload button above we might use:

$.fn.dataTable.ext.buttons.reload = {
    text: 'Reload',
    action: function ( e, dt, node, config ) {
        dt.ajax.reload();
    }
};

$('#myTable').DataTable( {
    ajax: '/api/data',
    buttons: [
        'reload'
    ]
} );

This concept of creating plug-in buttons is explored further in this example.

If you create a plug-in button that you would like to share with the DataTables community, we would be delighted to hear from you!