TinySort icon indicating copy to clipboard operation
TinySort copied to clipboard

Sort on date column in table

Open swombell opened this issue 3 years ago • 0 comments

Hi

I have html tables with date columns and am at a loss to know how to sort on the date column. I could add another hidden column with EPOCH time (ie seconds since epoch) which would then be a normal numeric order. But if the user clicked on the displayed table header, how would you make tinysort use a different(hidden) table column?

My date columns are formated d/m/Y, such as 7/6/2021 A table could have more than one date column. I want the user to be able to click on any tableheader to sort that column, which the code below achieves but dates sorting as strings is not correct.

For adding tinysort functionality to tables I use this code:

function add_sortable_table_header(table_id){
	var table = document.getElementById(table_id);
	var tableHead=table.querySelector('thead');
	var tableHeaders=tableHead.querySelectorAll('th');
	var tableBody=table.querySelector('tbody');
	tableHead.addEventListener('click',function(e){
	    var tableHeader = e.target,textContent = tableHeader.textContent,tableHeaderIndex,isAscending,order;
	    if (textContent!=='add row') {
	        while (tableHeader.nodeName!=='TH') {
	            tableHeader = tableHeader.parentNode;
	        }
	        tableHeaderIndex = Array.prototype.indexOf.call(tableHeaders,tableHeader);
	        isAscending = tableHeader.getAttribute('data-order')==='asc';
	        order = isAscending?'desc':'asc';
	        tableHeader.setAttribute('data-order',order);
	        tinysort(tableBody.querySelectorAll('tr'),{selector:'td:nth-child('+(tableHeaderIndex+1)+')',order: order});
	    }
	});
}

Tks ~S

swombell avatar Jun 21 '21 11:06 swombell