I have a dropdown list with Descending and Ascending for users to choose. I have to sort my DataTables based on the dropdown list that user select. For example, if user selects Ascending, I will sort the DataTables in the Ascending Order. Is there a way I can implement it in my codes? Thanks.
<script>
$.fn.dataTable.ext.search.push(
function( settings, data, dataIndex ) {
var select_value = $('#select_value').val();
var select_column = $('#select_column').val();
var column_index = '';
//var column = data[1] || 0; // use data for the age column
if ( select_value == '' || select_column == '' )
{
return true;
}
else {
//get the column name of data table
var column = 0;
$('#dataTable_table thead tr th').each(function(){
if( $(this).text() == select_column.toString())
{
return false;
}
column = column + 1;
});
column = data[column] || 0;
if(column!==0 && column.indexOf(select_value.toString()) >= 0)
{
return true;
}
}
return false;
}
);
$.fn.dataTableExt.sErrMode = 'throw';
$(document).ready(function () {
var table = $('#dataTable_table').DataTable();
$('#select_value').keyup( function() {
table.draw();
});
});
$(document).ready(function() {
$('#example').DataTable();
// this is for select dropdown when change
$('.toSort').on('change',function(){
var thisValue = $(this).val();
var ThisSort = $(this).attr('data-sort');
// trigger click on (1) mean first column .. you can change (1) to (2) and see the result
var column = $('#example thead tr th:nth-child(1)');
// make if statement to check which option user choose
if(thisValue == 'asc' && ThisSort !== 'asc'){
// trigger click
column.trigger('click');
$(this).attr('data-sort', 'asc');
}else if(thisValue == 'des' && ThisSort !== 'des'){
column.trigger('click');
$(this).attr('data-sort', 'des');
}
});
} );