dataTable page length change issue - javascript

I am using dataTable 1.10. Everything works well but I got following situation. I think that dataTable not support this behaviour.
By default I set the page length be 10, then I click Next page, table display items from 11 to 20. NOW I change the page length to 25, table display item from 11 to 35. This is not the thing I suppose to have. Whenever I change the page length, I wish to display from 1st item.
Is it possible to handle the Page Length change event in dataTable and customize that function?
Thank for reading. Hope to receive help from you.
var tableHdr = '<table cellpadding="0" cellspacing="0" border="0" class="display" id="alertsList">'
+ '<thead><tr>'
+ '<th>Level</th><th>Monitor Name</th><th>Alert Message</th><th>Raised At</th><th>Action</th>'
+ '</tr></thead></table>';
$('#overview_content').html( tableHdr );
//global variable
oTable = $('#alertsList').dataTable( {
"pagingType": "full_numbers",
"bJQueryUI": true,
"aaData": alertsData,
"bAutoWidth": false,
"aaSorting" : [[3, "desc"]],
"aoColumns": [
{ "sTitle": "Level", "mData":"alert_level", "sWidth":"10%" },
{ "sTitle": "Monitor Name", "mData":"monitor_name", "sWidth":"20%" },
{ "sTitle": "Alert Message", "mData":"alert_message", "sWidth":"30%" },
{ "sTitle": "Raised At", "mData":"triggered_datetime", "sWidth":"20%"},
{ "sTitle": "Action", "mData":"id", "bSortable":false, "bSearchable":false, "sWidth":"20%"}
],
"columnDefs": [
{
"targets": 1,
"data":"monitor_name",
"render": function ( data, type, full, meta ) {
return escapeHTML(data);
}
},
{
"targets": 2,
"data":"alert_message",
"render": function ( data, type, full, meta ) {
if (data == null || typeof data == 'undefined')
{
return "";
}
var description = data.length > 30? data.substr(0,30) + '...': data;
return escapeHTML(description);
}
},
{
"targets": 4,
"render": function ( data, type, full, meta ) {
return ("<span style='cursor:pointer' id='dismiss_alert_" + full.id + "' class='dismiss'>Dismiss</span> | " +
"<span style='cursor:pointer' id='delete_alert_" + full.id + "' class='delete'>Delete</span> | " +
"<span style='cursor:pointer' id='details_alert_" + full.id + "' class='details'>Details</span>");
}
} ]
} );

Try this, I found it from datatable forum.
var t = $('#table-id').dataTable();
$('#length li').click(function () {
redrawWithNewCount(t, this.id);
});
function redrawWithNewCount(t, row_count) {
//Lifted more or less right out of the DataTables source
var oSettings = t.fnSettings();
oSettings._iDisplayLength = parseInt(row_count, 10);
t._fnCalculateEnd(oSettings);
/* If we have space to show extra rows (backing up from the end point - then do so */
if (oSettings.fnDisplayEnd() == oSettings.fnRecordsDisplay()) {
oSettings._iDisplayStart = oSettings.fnDisplayEnd() - oSettings._iDisplayLength;
if (oSettings._iDisplayStart < 0) {
oSettings._iDisplayStart = 0;
}
}
if (oSettings._iDisplayLength == -1) {
oSettings._iDisplayStart = 0;
}
t.fnDraw(oSettings);
return t;
}

Related

Display Show More / Show Less option if text if more then 20 length

I try to add option in my Debatable column Description if text length is more then 20 character long display Show more option and collapse this column.
I try couple of option and one which work for me is something like this
function loadDataTable() {
dataTable = $('#tblData').DataTable({
"ajax": {
"url": "/Manager/Ticket/GetAll"
},
"columnDefs": [{
"targets": 0,
"data": "description",
"render": function (data, type, row, meta) {
return type === 'display' && data.length > 20 ?
'<span title="' + data + '">' + data.substr(0, 17) + '...</span>' :
data;
}
}],
"columns": [
{
"data": "description",
"width": "10%",
//"render": function (data) {
// return 'Prikazi vise'
//}
},
{ "data": "shortDescription", "width": "10%" },
{ "data": "dateAndTime", "width": "10%" },
{ "data": "ticketType.name", "width": "10%" },
{ "data": "status", "width": "10%" },
{
"data": "applicationUser.name",
"width": "10%",
"render": function (data) {
return '<a id="' + data + '" class="text-info user-details" data-toggle="modal" data-target="#userDetails" href="' + data + '" target_blank>' + data + '</a>'
}
},
{
"data": "id",
"render": function (data) {
return `
<div class="text-center">
<a href="/Manager/Ticket/Details/${data}" class="btn btn-success text-white" style="cursor:pointer">
<i class="fas fa-info-circle">Detalji/Chat</i>
</a>
<a href="/Manager/Ticket/Upsert/${data}" class="btn btn-primary text-white" style="cursor:pointer">
<i class="fas fa-edit">Uredi</i>
</a>
</div>
`;
}, "width": "15%"
}
]
});
}
After I add columnsDef
"columnDefs": [{
"targets": 0,
"data": "description",
"render": function (data, type, row, meta) {
return type === 'display' && data.length > 20 ?
'<span title="' + data + '">' + data.substr(0, 17) + '...</span>' :
data;
}
}],
This option works but only when User hover column it display text. I add ... and I want to create that this tree dots needs to be as <a> and should be clickable and when user click it needs to Show More and Show Less option.
I check couple of post here starting from this
REFERENCE 1
The problem here is that I am noob in jQuery and JavaScript and I have no idea how to implement this side.
This is how it look like right now
UPDATE
I found some solutions but doesn't work at all. I change my columnDef
"columnDefs": [{
"targets": 0,
"data": "description",
"render": function (data, type) {
return type === 'display' && data.length > 20 ?
'<span id="outer" data-shrink="' + data.substr(0, 17) + '" title="' + data + '"></span><span id="show">...</span>' :
data;
}
}],
Here is my JavaScript
$(document).ready(function () {
$(".tblData").hide();
$(".showmore").on("click", function () {
var txt = $(".tblData").is(':visible') ? 'Vise' : 'Manje';
$(".showmore").text(txt);
$(this).next('.tblData').slideToggle(200);
});
});
I successfully add ... to be clickable, but when I click text is not showing.
UPDATE
"columnDefs": [{
"targets": 0,
"data": "description",
"render": function (data, type) {
return type === 'display' && data.length > 20 ?
'<span id="outer" title="' + data + '">' + data.substr(0, 17) + '</span><span id="show">...</span>' :
data;
}
}],
$('#show').click(function () {
var text = $('#outer').attr('title');
$(this).text(text);
$('#show').after('<a id="less" onclick="someFunction()" href="#"> Show less</a>');
$('#outer').text('');
});
function someFunction() {
console.log('test');
$('#less').remove();
var txt = $('#outer').attr('data-shrink');
$('#show').text('');
$('#outer').text(txt);
$('#show').text('...');
}
var len = $('#outer').text();
if(len.length > 20) {
var txt = $('#outer').attr('data-shrink');
console.log(txt);
$('#outer').text(txt);
$('#show').text('...');
}
$('#show').click(function() {
var text = $('#outer').attr('title');
console.log('text', text.length);
$(this).text(text);
$('#show').after('<a id="less" onclick="someFunction()" href="#"> Show less</a>');
$('#outer').text('');
});
function someFunction() {
console.log('test');
$('#less').remove();
var txt = $('#outer').attr('data-shrink');
$('#show').text('');
$('#outer').text(txt);
$('#show').text('...');
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span id="outer" data-shrink="Das ist ein" title="Das ist ein ganzer Text langer Text">Das ist ein sehr langer Text</span><span id="show"></span>
Just replace the html with your variables.

What is the best way to extract all rows from Datatables under a criteria in Javascript

I'm currently working on a condominum program. The goal of this issue is when one Apartment row is clicked on the Parent table all the months - related to that apartment - must be displayed on the Child table.
The click/select/deselect is working fine but I can not obtain all the twelfth months.
This is my actual tables layout (example 1):
And this is my actual tables layout (example 2):
My code to childTable is:
var childTable = $('#child').DataTable( {
"pageLength": 12,
ajax: {
url: "ajax/query_pagquotas.php", // This is the URL to the server script for the child data
dataSrc: function (data) {
var selected = parentTable.row( { selected: true } );
if ( selected.any() ) {
var ID = selected.data().ID;
for (var i=0; i < data.data.length; i++) {
var rows = data.data[i];
if (rows.ID === ID) {
return [rows];
}
}
} else {
return [];
}
}
},
columns: [
{ "data": "ID" },
{ "data": "DATA" },
{ "data": "MES" },
{ "data": "VALOR" },
{ "data": "METODO" },
{ "data": "ESTADO" },
{ "data": "OBS" }
]
} );
Thanks for your help Masters
[edited]
Ups! If condition at the end does not make the 'deselect' work...
This is my full code at the moment:
$(document).ready(function() {
var parentTable = $('#parent').DataTable( {
ajax: "ajax/dbfraccoes.php",
"language": {
"sSearchPlaceholder": "Apto ou Proprietário...",
"url": "//cdn.datatables.net/plug-ins/9dcbecd42ad/i18n/Portuguese.json",
},
"processing": true,
"scrollY": "200px",
"scrollCollapse": true,
"paging": false,
pageLength: 5,
select: {
style: 'single'
},
columns: [
{ "data": "ID","searchable": false },
{ "data": "APTO" },
{ "data": "FRACCAO"},
{ "data": "PROPRIETARIO" },
{ "data": "VALOR_QUOTA","searchable": false, className: "cssValores"},
{ "data": "OBS" }
]
} );
// tabela Child ------------------------------------------
var childTable = $('#child').DataTable( {
columnDefs: [{
targets: 6,
render: function(data, type, row, meta){
if(type === 'display' && data === 'EMITIDO'){
data = '<td style="text-align:center"><button type="button" class="btn btn-info btn-sm cssButton center" title="Emitido Aviso de Recibo a pagamento">EMITIDO</button></td>'+
'<div class="links">' +
'Editar ' +
'</div>';
}else if (type === 'display' && data === 'AGUARDA'){
data = '<td style="text-align:center"><button type="button" class="btn btn-warning btn-sm cssButton center" title="Limite de pagamento ultrapassado. Em período de tolerância.">AGUARDA</button></td>'+
'<div class="links">' +
'<a href="<?php echo WEB_URL;?>credit_debit/gest_quotas.php?spid='+
row['pqid']+'#insert">Editar</a> ' +
'</div>';
}
return data;
}
}],
"paging": false,
"searching": false,
"language": {
"zeroRecords": "<center>Clique na tabela acima, na linha do apartamento que pretende. <br/>Os dados da fracção/apartamento selecionado acima serão reflectidos nesta tabela</center>",
},
ajax: {
url: "ajax/query_pagquotas.php",
dataSrc: function (data) {
var selected = parentTable.row( { selected: true } );
if ( selected.any() ) {
var rows = []; // create an empty array
var ID = selected.data().ID;
for (var i=0; i < data.data.length; i++) {
var row = data.data[i];
if (row.ID === ID) {
rows.push(row);
}
}
}
return rows;
},
},
columns: [
{ "data": "pqid" },
{ "data": "ID"},
{ "data": "DATA" },
{ "data": "MES"},
{ "data": "VALOR", className: "cssValores"},
{ "data": "METODO" },
{ "data": "ESTADO" },
{ "data": "OBS" }
]
} );
// This will load the child table with the corresponding data
parentTable.on( 'select', function () {
childTable.ajax.reload();
} );
//clear the child table
parentTable.on( 'deselect', function () {
childTable.ajax.reload();
} );
} );
The simplest way to adjust your existing code, is to change the logic in your dataSrc: function (data) {...}.
At the moment, you are only creating an array of one item.
So, instead you can do this:
dataSrc: function (data) {
var selected = parentTable.row( { selected: true } );
var rows = []; // create an empty array
if ( selected.any() ) {
var ID = selected.data().ID;
for (var i=0; i < data.data.length; i++) {
var row = data.data[i]; // change the variable name to "row"
if (row.ID === ID) {
rows.push(row); // add the new row to your array of rows
}
}
}
return rows; // return your array of rows
}
The most important line here is: rows.push(row); which is how JavaScript adds a new item to the end of an array.
So, now at the end of your dataSrc function you will either have an empty array [] if no rows were selected, or you will have an array of rows which match your ID.
That should solve your current problem.
The above approach should work - but it involves fetching every child row, every time - and then filtering out the ones you do not want to show.
You can probably improve on this by submitting the ID of the selected row as part of the child table's ajax URL. You can move the relevant code from its current location into your parentTable's on(select) function:
var selectedID = -1
parentTable.on( 'select', function () {
var selected = parentTable.row( { selected: true } );
if ( selected.any() ) {
selectedID = selected.data().ID;
}
childTable.ajax.reload();
} );
I do not know how you have implemented your ajax/query_pagquotas.php, so I am not sure of the best way to pass the selectedID parameter to it.
Normally I would append it as a query parameter in your ajax parameters:
data: 'id=' + selectedID
You may already know how to do this yourself.
Once you have passed the selectedID to your PHP, then you can use it to return only the records you want to display - and you can remove all of the existing dataSrc: function (data) {...} logic from your child table definition.

how to remove other row based on selected row value?

i try to remove all row that has not equal to "acctname" and once I click 1 row nothing happen ? im using check box and function to get the value of selected row.
var TableExcess;
$(function () {
TableExcess = $('#PaymentExcess').DataTable({
"scrollY": '50vh',
"scrollCollapse": true,
"paging": false,
//"searching": false,
"ajax": "#Url.Action("GetPaymentExcess", "payable")",
"columns": [
{
"render": function (data, type, full, meta) {
return "<input type='checkbox' class='checkbox' onclick='addavailable(" + full.Id + ", " + full.AvailableAmount + ", \"" + full.AccountName + "\", this.checked)'>"
}
},
{ "data": "Id" },
{ "data": "AccountName" },
{ "data": "PaidAmount" },
{ "data": "AvailableAmount" },
]
});
});
function addavailable(id, amount, acctname, isChecked)
{
var filteredData = TableExcess
.column( 2 )
.data()
.filter( function ( value, index ) {
return TableExcess.row(value).data()[2] != acctname;
})
TableExcess.rows( filteredData )
.remove()
.draw();
}

Using "later" variable in jQuery DataTables

My DataTables configuration is something like this:
(function ($) {
"use strict";
$(document).ready(function () {
$('#data-table-users').DataTable({
"processing": true,
"serverSide": true,
"filter": true,
"orderMulti": false,
"ajax": {
"url": "/Users/GetUsersData",
"type": "POST",
"datatype": "json"
},
"columnDefs":
[{
"targets": [0],
"visible": false,
"searchable": false
}],
"columns": [
.............................
{
"data": "Image",
"orderable": false,
"render": function (data, type, row, meta) {
var imgSrc;
if (data != null) {
imgSrc = '"data:image/jpeg;base64,' + atob(data) + '"';
}
else {
imgSrc = "/svg/" + "A" + ".svg";
}
return '<div><img class="small-img" src=' + imgSrc + '></div>';
}
},
{
"data": "UserName",
"render": function (data, type, row, meta) {
return '<div class="positioned"> <div class="editable" data-name="userName" contenteditable="true">'
+ data + '</div > <i class="fa fa-pencil pushright" aria-hidden="true"></i> </div>';
}
},
{
"data": "FirstName",
"render": function (data, type, row, meta) {
if (data == null)
data = "";
return '<div class="positioned"> <div class="editable" data-name="userName" contenteditable="true">'
+ data + '</div > <i class="fa fa-pencil pushright" aria-hidden="true"></i> </div>';
}
},
............................
],
"order": [[8, "desc"]]
});
});
})(jQuery);
For Image column I have in the Render function:
else {
imgSrc = "/svg/" + "A" + ".svg";
}
What I would like is instead of having imgSrc = "/svg/A.svg" is to construct it based on UserName column like so:
imgSrc = "/svg/" + userName[0].toUpperCase() + ".svg";
How can I do that without changing code on server side? It seems to me that DataTables is rendering UserName cell at a later time, so Image cell is already rendered. Can somehow a trigger be added when UserName is rendered to alter Image cell content?
I can change the values for all cells in Image column after the whole table gets rendered, but somehow I dislike that idea because it might look ugly. So, please, don't suggest that.
Just got it. I can access all data for the current row using row parameter.
So it's just:
imgSrc = "/svg/" + row['UserName'][0].toUpperCase() + ".svg";

Function to get row data works only in responsive mode in Datatables

When I click on the image in Reponsive mode, it will return the row data in console. But in normal view I get Undefined error.
var table = $('.dataTable').DataTable({
"responsive": true,
"columnDefs": [{
"targets": 4,
"data": null,
"render": function (data, type, full, meta) {
if (type === 'display') {
data = "<a href='#' width='30px' class='editMe' data='" + full[0] + "'><img src='/images/edit.png' width='30px' /></a>";
}
return data;
}
} ,
{
"targets": 0,
"visible": false,
"searchable": false
}]
});
$('.dataTable').on('click', '.editMe', function () {
console.log(table.row(this).data());
});
Use the code below instead:
$('.dataTable').on('click', '.editMe', function () {
var $row = $(this).closest('tr');
if($row.hasClass('child')){ $row = $row.prev(); }
console.log(table.row($row).data());
});
See this example for code and demonstration.

Categories