arrow_back
Back

DataTables jQuery plugin: install, setup, and usage

Andrew Dorokhov Andrew Dorokhov schedule 2 min read
menu_book Table of Contents

open_in_new Home page .

Installation

We need only include two files in your page:

  • The DataTables Javascript file.
  • The DataTables CSS file.

We can download files here: open_in_new https://datatables.net/download/

Using

Table example:

<table id="table_id" class="display">
    <thead>
        <tr>
            <th>Column 1</th>
            <th>Column 2</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>Row 1 Data 1</td>
            <td>Row 1 Data 2</td>
        </tr>
        <tr>
            <td>Row 2 Data 1</td>
            <td>Row 2 Data 2</td>
        </tr>
    </tbody>
</table>
$(function () {
    $('#table_id').DataTable();
});

AJAX source

Frontend:

$('#chairs-list').DataTable({
    ajax: ajaxurl + '?action=get_chairs',
    columns: [
        { data: 'name' },
        { data: 'image_url' },
        { data: 'badge_url' },
        { data: 'link' }
    ]
});

Backend:

$chairs = Chair_Picker_Tool_Table::get_all();

echo json_encode( [ 'data' => $chairs ] );

die();

Render data

We can customize rendering data as we like.

columns: [
    { data: 'id', width: '90px' },
    { data: 'name' },
    { data: 'min_weight' },
    { data: 'max_weight' },
    {
        data: 'image_url',
        render: function ( link, type ) {
            if (type === 'display') {
                return '<a href="' + link + '" target="_blank" class="button">&#128444; Open</a>';
            }
            return link;
        }
    },
    ...

Options

$('#example').DataTable( {
    paging: false,  // Disable paging.
    pageLength: 25, // Default items number per page.
    "processing": true, // Show an animated processing indicator.
} );

Some useful cases

open_in_new Flexible table width :

<table id="example" class="display" style="width:100%">
    ...
</table>

open_in_new CSS classes for styling .

code

Need Help with Development?

Happy to help — reach out via the contacts or go straight to my Upwork profile.

work View Upwork Profile arrow_forward