Ordering filter options by value and not text
Ordering filter options by value and not text
evidentoli
Posts: 2Questions: 1Answers: 0
Hi everyone, forgive me if this has already been answered.
I'm using the dropdown filters using AJAX on my datatables table. When displaying the date, the filtering orders them in alphabetical order and not numerical order based on the option's value. See below screenshot:
I want to filter these by the most recent date desc.
My code for the filtering is shown below:
this.api().columns([0,1,2,3,4,5,6,7,8]).every( function (index) {
var select = $('<select class="w-full shadow-sm sm:text-sm border-gray-300 rounded-md focus:border-miq-green js-filter-column"><option value="">Show all</option></select>')
.appendTo($(column.header()))
.on( 'change', function () {
$('.js-filter-column').attr('disabled', 'disabled');
var val =
$(this).val()
;
column
.search( val ? val : '', true, false )
.draw();
} );
column.data().unique().sort().each( function ( d, j ) {
// date fields pass value through in special format
if (index === 6 || index === 7) {
const months = ["January","February","March","April","May","June","July","August","September","October","November","December"];
const date = new Date(d);
let monthName = months[date.getMonth()],
month = (date.getMonth() + 1).toString().padStart(2, "0"),
year = date.getFullYear();
select.append( '<option value="'+year+ '-'+month+'">'+ monthName + ' ' + year +'</option>' )
} else if (d !== "" && d !== null) {
select.append( '<option value="'+d+'">'+d+'</option>' )
}
} );
} );
Thanks in advance
Answers
Sound like you will need to change the loop i line 15 (
column.data().unique().sort().each(..)
to sort differently. You might need different loops; one for the date order and the other using the sort() method. Its hard to say exactly what you need to do but if you need help please build a test case with an example your data so we can see exactly what you have.https://datatables.net/manual/tech-notes/10#How-to-provide-a-test-case
Kevin
@kthorngren I have created a test case although I use AJAX on my actual call and the test case shows the ajax but I've hard coded some data in. Hope this helps.
http://live.datatables.net/tikakefa/3/edit