Sorting Boolean Columns In JQuery Datatables
Recently I had some data in a table and was using the excellent front-end library jQuery Datatables to interact with the data. One of the columns was boolean and was not sorting correctly. I googled around the internet and hacked together a solution that worked for me.
First off, you have to add some hidden html to your table. In my case, I was storing the booleans as an interactive column of buttons the user could toggle with an onclick
event. So I was starting off with some HTML that looked like this for true
columns:
And looked like this for false
columns:
Basically just a red/green button depending on the state, pretty amazing shit I know. So I first added two hidden div
tags in each of these table data tags using an html data tag to specify if it was true
or false
using zero or one.
And looked like this for false
columns:
For all you beginners out there, pay attention to the data-sort
attribute.
Next, I needed to “dive” into some javascript and tell datatables how to sort this data:
Here I’m simply pulling the value out of the data-sort
attribute, converting it to an integer, and then doing a simple comparision for both ascending and decending sort.
I needed to tell the datatable what type of column I was using.
In my case, my new column was living in column 5 in my table. Finally, I forced the table to sort in decending order by default, refreshed, and boom, I am now sorting booleans.
I hate javascript, but if you like articles like this, follow me on twitter @josephmisiti