Now Reading
Quick and easy datatables with jquery
0

Quick and easy datatables with jquery

by Simon ParkerJuly 23, 2020

You want a nice looking, easy to use, table to display some data.

You can spend some time custom coding the table with various sorting functions and perhaps hiding the odd column but that’s all done for you already. Using Jquery Datatables.

I will show a couple of quick examples on how I now use the datatables Jquery plugin to quickly be able to control various functions of the table to make it simple and easy to use.

First off you include the two required files, A Css file and a JS file.

//cdn.datatables.net/1.10.21/css/jquery.dataTables.min.css
//cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js

Then you can just include one piece of js code in your project to convert the normal table into a really nice interactive datatable.

$(document).ready( function () {     $('#myTable').DataTable(); } );

This will target a table which has the id of myTable and then automatically converts it to a datatable.

So to go a little more complex let’s look at a page I have just completed.

I am using Flask and passing in an object from an SQLAlchemy model called lists

return render_template("lists/index.html", lists=lists)

Then within that HTML Jinja2 template I first create the table headings and I am then using a for loop to generate the table.

<table id="lists-data-table" class="table table-striped table-bordered table-td-valign-middle">
   <thead>
      <tr>
         <th width="1%">#</th>
         <th width="5%">Type</th>
         <th width="45% class="text-nowrap">Name</th>
         <th width="10% class="text-nowrap">URLs</th>
         <th width="20% class="text-nowrap">Status</th>
         <th width="20% class="text-nowrap">Actions</th>

      </tr>
   </thead>
   <tbody>

   {% for list in lists %}
          <tr class="{{ loop.cycle('odd', 'even') }}">
            <td>{{ list.id }}</td>
            <td style="text-align:center">
            {% if list.type == "csv" %}
                <i class="fa fa-file-excel-o"></i>
            {% elif list.type == "single" %}
                <i class="fa fa-search"></i>
            {% endif %}
            </td>
            <td>{{ list.name }}</td>
            <td>{{ list.amount_of_urls }}</td>
            <td>{{ list.status }}</td>
            <td>{{ list.actions }}</td>
          </tr>
   {% endfor %}

   </tbody>
</table>

You can see that I already have some Bootstrap classes applied to the table so you can either ignore these for now or use this within a template that has BS4 css and js included.

So, I now have a table. It shows the data I want as is basically a good table. However if I pass through a couple of hundred items within the lists object then this is a really long table… and I also want to be able to order the lists in an effective way plus hide one column and stop another from being sortable.

So, I make a new js file to include in this page only that initializes the datatable.

var handleDataTableDefault = function() {
	"use strict";
    
	if ($('#lists-data-table').length !== 0) {
		$('#lists-data-table').DataTable({
			responsive: true,
			"order": [[ 0, "desc"]],
			"columnDefs": [
            {
                "targets": [ 0 ],
                "visible": false,
                "searchable": false
            },
			{
				"targets": [ 1 ],
				"orderable": false
			}
        ]
		});
	}
};

var TableManageDefault = function () {
	"use strict";
	return {
		//main function
		init: function () {
			handleDataTableDefault();
		}
	};
}();

$(document).ready(function() {
	TableManageDefault.init();
});

This may look a little complex but all it is doing is separating out the different stages of the datatable initialisation so that we can easily update it and or add new code easily. For example if we had two tables on the page we could add a second entry in the init: function and have a second table managed with different options.

The top var hanldeDataTableDefault function is the one we need to look at anyway.

Inside the if statement it first checks the see if there is a div with the id of lists-data-table, if there is it initialises it with $(‘#lists-data-table’).Datatable as per the above, But it also passes in some options.

responsive: true, should be quite self-explanatory. but the reason I added this in is because of the entry below that.

"order": [[ 0, "desc"]],

This tells the datatable that when it first displays order using the first column and make it descending. fairly simple.

But I don’t want the actual ordering column to show as it contains randomly generated id’s and is not very intuitive.

"columnDefs": [
         {
             "targets": [ 0 ],
             "visible": false,
             "searchable": false
         },

This columnDefs option is where I can specify different arguments for each column, the first column is 0 so I target this and set visible to false and also searchable to false.

This now only functions as the way to default sort when the page loads. with the ID being sorted in descending order and then hidden as I want the latest list to show first but then allow the user to reorder using other columns if they want to.

I also added in a second column def to stop my “Type” column from being orderable as it just contains some font awesome icons.

{
   "targets": [ 1 ],
   "orderable": false
}

This targets the second Column and makes is not orderable.

Very simple once you get the basics and it opens up a wide range of additional functions which you can find on the datatables website. For example, to change the default amount of rows shown on load i can add a default option like so

$('#example').dataTable( {
  "pageLength": 50
} );

This would then default to having 50 rows shown when the table loads preventing a massive long page where the lists object contains possibly hundreds of lists.

There are many other more advanced topics covered on the datatables.net website which I would encourage you to read through.

As usual, comments are welcome.

And for those who don’t like my writing style. Me either. This is more for me to remember stuff than a tutorial but any constructive criticism is welcome if I can improve the flow of the article.

What's your reaction?
Love It
100%
Interested
0%
Meh...
0%
What?
0%
Hate It
0%
Sad
0%
About The Author
Simon Parker

Leave a Response