JQuery Datatable - Sort by multiple columns if necessary - javascript

I have this html table:
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<table class="table table-bordered" id="resourcesActivitysTable">
<thead>
<tr>
<th>Order</th>
<th>Priority</th>
<th>Date</th>
</tr>
</thead>
<tbody>
<tr>
<td>SomeString</td>
<td>1</td>
<td>28.09.2018</td>
</tr>
<tr>
<td>SomeString</td>
<td>3</td>
<td>20.09.2018</td>
</tr>
<tr>
<td>SomeString</td>
<td>1</td>
<td>27.09.2018</td>
</tr>
</tbody>
</table>
This is my Datatable Configuration:
$('#resourcesActivitysTable').dataTable({
//"order": [[ 1, 'asc' ]],
"aaSorting": [[1, "asc"]],
"iDisplayLength": 10,
"paging": true,
"lengthChange": false,
"searching": false,
"ordering": true,
"info": true,
"autoWidth": false,
"language": {
"sEmptyTable": "Keine Daten in der Tabelle vorhanden",
"sInfo": "_START_ bis _END_ von _TOTAL_ Einträgen",
"sInfoEmpty": "0 bis 0 von 0 Einträgen",
"sInfoFiltered": "(gefiltert von _MAX_ Einträgen)",
"sInfoPostFix": "",
"sInfoThousands": ".",
"sLengthMenu": "_MENU_ Einträge anzeigen",
"sLoadingRecords": "Wird geladen...",
"sProcessing": "Bitte warten...",
"sSearch": "Suchen",
"sZeroRecords": "Keine Einträge vorhanden.",
"oPaginate": {
"sFirst": "Erste",
"sPrevious": "Zurück",
"sNext": "Nächste",
"sLast": "Letzte"
},
"oAria": {
"sSortAscending": ": aktivieren, um Spalte aufsteigend zu sortieren",
"sSortDescending": ": aktivieren, um Spalte absteigend zu sortieren"
}
},
"fnDrawCallback": function (nRow, aData, iDisplayIndex, iDisplayIndexFull) {
var table = $('#resourcesActivitysTable').DataTable()
table.rows().every(function (rowIdx, tableLoop, rowLoop) {
var data = this.data();
// getOrderStatus(data.orderID);
});
}
});
The Datatable sort the Data by the second column (Priority).
My problem is, if the Priority is the same, the table should be sorted by the Date column.
This is my wish result:
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<table class="table table-bordered" id="resourcesActivitysTable">
<thead>
<tr>
<th>Order</th>
<th>Priority</th>
<th>Date</th>
</tr>
</thead>
<tbody>
<tr>
<td>SomeString</td>
<td>1</td>
<td>27.09.2018</td>
</tr>
<tr>
<td>SomeString</td>
<td>1</td>
<td>28.09.2018</td>
</tr>
<tr>
<td>SomeString</td>
<td>3</td>
<td>20.09.2018</td>
</tr>
</tbody>
</table>
Anyone here an idea how i can sort the Table Data by Date if the priority is the same?

We can able to do sorting with multiple columns in datatable. Please check below code,
"order": [[ 0, 'desc' ],[ 1, 'asc' ]]
In the above, 0 indicates the first column in a table. 1 indicates the second column.

Related

DataTables: Header and body not aligned

I have a select combobox to show/hide a div where there's a DataTable. The problem is that when the div is shown the DataTable header and body are not aligned. The DataTable get populated from database using php.
UPDATE
If the div is not hidden when the page is loaded, the datatable loads
aligned. It gets misaligned when it is hidden and is show by using the
select combobox.
Code:
<table id="dtBasicExample" class="table table-striped table-bordered table-sm" cellspacing="0" width="100%">
<thead>
<tr>
<th>Código<i class="fa fa-sort"></i></th>
<th>Producto<i class="fa fa-sort"></i></th>
<th>% Exo.<i class="fa fa-sort"></i></th>
</tr>
</thead>
<tbody>
</tbody>
<tfoot>
</tfoot>
</table>
<script>
$(document).ready(function(){
$($.fn.dataTable.tables(true)).DataTable()
.columns.adjust();
$.noConflict(true);
//cambiar idioma de Tabla
$('#dtBasicExample').DataTable({
"scrollX": true,
"order": [[1, "asc"]],
"language":{
"lengthMenu": "Mostrar _MENU_ registros por pagina",
"info": "Mostrando pagina _PAGE_ de _PAGES_",
"infoEmpty": "No hay registros disponibles",
"infoFiltered": "(filtrada de _MAX_ registros)",
"loadingRecords": "Cargando...",
"processing": "Procesando...",
"search": "Buscar:",
"zeroRecords": "No se encontraron registros coincidentes",
"paginate": {
"next": "Siguiente",
"previous": "Anterior"
},
}
});
$('.dataTables_length').addClass('bs-select');
});
</script>
Output

how to save my datatable data ASP.NET MVC 5

I need to save all the data that is in my datatable
How could I add a general button that keeps everything in my datatable?
This in my current Project :
var table = $('#listaDocumentos').DataTable({
dom: 'Bfrtip',
buttons: [
'copy', 'csv', 'excel', 'pdf'
],
language: {
"decimal": "",
"emptyTable": "No hay información",
"info": "Mostrando _START_ a _END_ de _TOTAL_ Documentos",
"infoEmpty": "Mostrando 0 to 0 of 0 Documentos",
"infoFiltered": "(Filtrado de _MAX_ total entradas)",
"infoPostFix": "",
"thousands": ",",
"lengthMenu": "Mostrar _MENU_ Documentos",
"loadingRecords": "Cargando...",
"processing": "Procesando...",
"search": "Buscar:",
"zeroRecords": "Sin resultados encontrados",
"paginate": {
"first": "Primero",
"last": "Ultimo",
"next": "Siguiente",
"previous": "Anterior"
}
}
});
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css">
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/buttons/1.5.2/css/buttons.dataTables.min.css"> <script type="text/javascript" language="javascript" src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script type="text/javascript" language="javascript" src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<script type="text/javascript" language="javascript" src="https://cdn.datatables.net/buttons/1.5.2/js/dataTables.buttons.min.js"></script>
<script type="text/javascript" language="javascript" src="https://cdn.datatables.net/buttons/1.5.2/js/buttons.flash.min.js"></script>
<script type="text/javascript" language="javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.1.3/jszip.min.js"></script>
<script type="text/javascript" language="javascript" src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.36/pdfmake.min.js"></script>
<script type="text/javascript" language="javascript" src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.36/vfs_fonts.js"></script>
<script type="text/javascript" language="javascript" src="https://cdn.datatables.net/buttons/1.5.2/js/buttons.html5.min.js"></script>
<table id="listaDocumentos" class="table table-striped table-bordered" style="width:100%">
<thead>
<tr>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Age</th>
<th>Start date</th>
<th>Salary</th>
</tr>
</thead>
<tbody>
<tr>
<td>Tiger Nixon</td>
<td>System Architect</td>
<td>Edinburgh</td>
<td>61</td>
<td>2011/04/25</td>
<td>$320,800</td>
</tr>
<tr>
<td>Donna Snider</td>
<td>Customer Support</td>
<td>New York</td>
<td>27</td>
<td>2011/01/25</td>
<td>$112,000</td>
</tr>
</tbody>
<tfoot>
<tr>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Age</th>
<th>Start date</th>
<th>Salary</th>
</tr>
</tfoot>
</table>
What i understand from your question is
you need to save data which is currently showing in the view(Html page) as tabular format.
In this case you can use jquery or javascript like below to get the data.
var table = $("table tbody");
table.find('tr').each(function (i) {
// comment loop through the tr and get value of every td within this tr tag
var tds = $(this).find('td');
var Name = $tds.eq(0).text();
var Position = $tds.eq(1).text();
var office = $tds.eq(2).text();
var age = $tds.eq(3).text();
var startPosition = $tds.eq(4).text();
var salary = $tds.eq(5).text();
});
Then bind a button in view like
<input type="button" id="btn_data_save" value="Save Data"/>
Then an ajax call to pass the data to server. WIthin that call you need to collect all the value and build an array of object.
$(document).on('click','#btn_data_save', function(){
var ary=[];
var table = $("table tbody");
table.find('tr').each(function (i) {
var obj={};
obj.tds = $(this).find('td');
obj.name = $tds.eq(0).text();
obj.position = $tds.eq(1).text();
obj.office = $tds.eq(2).text();
obj.age = $tds.eq(3).text();
obj.startPosition = $tds.eq(4).text();
obj.salary = $tds.eq(5).text();
ary.Push(obj);
});
$.ajax({
type: 'POST',
url: '',
data: { list: JSON.stringify(ary) },
dataType: 'json',
success: function (data) {
}
});
});
Finally in controller
[HttpPost]
public ActionResult SaveData(string list)
{
//comment do your work
}
Please comment if you do not understand the solution. i will describe if necessary.

How to add extra field in datatable which is not database

I am trying to add edit and delete button in data table.
I have html
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>Theater name</th>
<th>Action</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Theater name</th>
<th>Action</th>
</tr>
</tfoot>
</table>
$(document).ready(function() {
$('#example').DataTable( {
"processing": true,
"serverSide": true,
"ajax": "<?php echo JRoute::_('index.php?option=com_wsmovies&task=addtheatres' ); ?>"
});
});
I tried adding column in thead and tbody but it is giving me alert saying
DataTables warning: table id=example - Requested unknown parameter '1' for row 0, column 1. For more information about this error, please see http://datatables.net/tn/4
Server returning data
{"draw":0,"recordsTotal":57,"recordsFiltered":57,"data":[["Tiger","Nixon"],["Garrett","Winters"],["Ashton","Cox"],["Cedric","Kelly"],["Airi","Satou"],["Brielle","Williamson"],["Herrod","Chandler"],["Rhona","Davidson"],["Colleen","Hurst"],["Sonya","Frost"],["Jena","Gaines"],["Quinn","Flynn"],["Charde","Marshall"],["Haley","Kennedy"],["Tatyana","Fitzpatrick"],["Michael","Silva"],["Paul","Byrd"],["Gloria","Little"],["Bradley","Greer"],["Dai","Rios"],["Jenette","Caldwell"],["Yuri","Berry"],["Caesar","Vance"],["Doris","Wilder"],["Angelica","Ramos"],["Gavin","Joyce"],["Jennifer","Chang"],["Brenden","Wagner"],["Fiona","Green"],["Shou","Itou"],["Michelle","House"],["Suki","Burks"],["Prescott","Bartlett"],["Gavin","Cortez"],["Martena","Mccray"],["Unity","Butler"],["Howard","Hatfield"],["Hope","Fuentes"],["Vivian","Harrell"],["Timothy","Mooney"],["Jackson","Bradshaw"],["Olivia","Liang"],["Bruno","Nash"],["Sakura","Yamamoto"],["Thor","Walton"],["Finn","Camacho"],["Serge","Baldwin"],["Zenaida","Frank"],["Zorita","Serrano"],["Jennifer","Acosta"],["Cara","Stevens"],["Hermione","Butler"],["Lael","Greer"],["Jonas","Alexander"],["Shad","Decker"],["Michael","Bruce"],["Donna","Snider"]]}
Can anyone help me solve this issue
You just need to add its HTML in your DataTable definition
$('#example').DataTable( {
"processing": true,
"serverSide": true,
"ajax": "<?php echo JRoute::_('index.php?option=com_wsmovies&task=addtheatres' ); ?>",
"columns": [
{
"targets": -1,
"data": null,
"orderable": false,
"defaultContent": [
"<i class='glyphicon glyphicon-edit'></i>"+
"<i class='glyphicon glyphicon-trash'></i>"]
}
]
} );
DEMO : https://jsfiddle.net/Prakash_Thete/evfchh7q/
Change your table definition as below(Added one more header as you are sending data for two columns + edit button column).
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>Theater name</th>
<th>One more header</th>
<th>Action</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Theater name</th>
<th>One more header</th>
<th>Action</th>
</tr>
</tfoot>
</table>

DataTables sorting not showing in descending order

Please solve my problem. I want to show descending order. By default it is ascending order.
Please check my code-
datTable.js
JS-
<script href="http://myshowcam.com/TestSite/assets/data-tables/jquery.dataTables.js"></script>
<script>
$('#dataTable').dataTable({
"sDom": "<'row'<'col-sm-6'l><'col-sm-6'f>r>t<'row'<'col-sm-6'i><'col-sm-6'p>>",
"sPaginationType": "bootstrap",
"oLanguage": {
"sLengthMenu": "_MENU_ records per page",
"oPaginate": {
"sPrevious": "Prev",
"sNext": "Next"
}
},
"aoColumnDefs": [{
'bSortable': false,
'aTargets': [0]
}]
});
</script>
HTML-
<table class="table table-striped border-top" id="dataTable">
<thead>
<tr>
<th class="hidden-phone"> #ID </th>
<th class="hidden-phone"> Username </th>
</tr>
</thead>
<tbody>
<tr>
<td>7</td>
<td>chinu</td>
</tr>
<tr>
<td>3</td>
<td>Debakanta</td>
</tr>
<tr>
<td>8</td>
<td>Sanjib</td>
</tr>
</tbody>
</table>
Above code by default i am getting asc record in the first column.
I want to customize above code. Need desc
You'll have to add an order property to your table configuration. Your version of datatables doesn't support the order property. I'd recommend updating to the latest version of datatables if you can.
$('#dataTable').dataTable({
order: [
[0, 'desc']
]
});
Here is the fiddle. (note: I had to comment out the paginate property, uncomment it in your code)
$('#example').DataTable( {
"aaSorting": [[ 0, "desc" ]] // Sort by first column descending
} );
http://live.datatables.net/pacirato/1/edit

scope = row not recognised in javascript code (jquery.visualize plugin)

I display a chart but I have to specify that my th column is (scope=row) in javascript code.
The chart used in this manner, Html code (example of using) :
<html>
<head>
<script language="javascript" type="text/javascript" src="jquery-1.10.2.min.js"></script>
<script language="javascript" type="text/javascript" src="jquery.visualize.plugin.js"></script>
<link type="text/css" rel="stylesheet" href="base.css"/>
<link type="text/css" rel="stylesheet" href="jquery.visualize.plugin.css"/>
<script type="text/javascript">
$(function(){
$('table').visualize({type: 'line'}).appendTo('body');
});
</script>
</head>
<body>
<table>
<caption>2009 Employee Sales by Department</caption>
<thead>
<tr>
<td></td>
<th scope="col">2010</th>
<th scope="col">2011</th>
<th scope="col">2012</th>
<th scope="col">2013</th>
<th scope="col">2014</th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row">Gastro</th>
<td>10</td>
<td>20</td>
<td>30</td>
<td>40</td>
<td>50</td>
</tr>
<tr>
<th scope="row">Pneumo</th>
<td>20</td>
<td>30</td>
<td>20</td>
<td>40</td>
<td>40</td>
</tr>
<tr>
<th scope="row">Procto</th>
<td>80</td>
<td>90</td>
<td>60</td>
<td>100</td>
<td>90</td>
</tr>
</tbody>
</table>
</body>
</html>
You can see that in tbody, for the th tags, we used scope="row".
I use a datatTable to fill the table and I want to know how to specify it in javascript code.
My javascript code :
function fillDataTable(data) {
if ($("#table_campaigns").css("visibility") == "hidden")
$("#table_campaigns").css("visibility", "visible");
$('#table_campaigns').dataTable({
'aaData': data,
'aoColumns': [
{ "sTitle": "", "sCellType": "th", "fnCreatedCell": function (cell) { cell.scope = 'row';}},
{ "sTitle": "2010" },
{ "sTitle": "2011" },
{ "sTitle": "2012" },
{ "sTitle": "2013" },
{ "sTitle": "2014" }
],
"iDisplayLength": 10,
"bJQueryUI": true,
"bDestroy": true,
"bPaginate": true,
"bLengthChange": false,
"bFilter": true,
"bSort": false,
"bInfo": false,
"bAutoWidth": false
});
}
I tested too $(tbody>th).attr('scope','row') but in vain.
Here is my chart :
This way works for me:
$('table tbody th').attr('scope','row');
You only want to use > when looking for direct childrens. th is not a direct children of tbody.
Also, you need to add quotes.
Live example

Categories