how to remove other row based on selected row value? - javascript

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();
}

Related

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.

Nested Datatable returns undefined rowData on Ajax call

*
My Task is to get Nested DataTbless after making an ajax call.
I'm Getting the function working. Everytime I make a call it returns the data in main Datatable.
But, On Ajax call it gives me rowData is undefined error in Nested datatable.
Since I'm new at using Jquery I couldn't figure out the logical solution.
*
function ts_data(tabledata,tableChild,Expected_hrs,Hours_logged,Working_days,table_month){
$(document).ready(function() {
var table=$('#example').DataTable( {
"data": tabledata,
"retrieve": true,
"columns": [{
className: 'details-control',
orderable: false,
data: null,
defaultContent: ''
},
{ "data": "Fullname"},
{ "data": "Hours" },
{ "data": "Present_Hours_month"},
{ "data": "Working_Days" },
{ "data": "Month_Year"}],
"order": [[1, 'asc']]
} );
function format ( rowData ) {
console.log(rowData);
var file = jQuery.grep(tableChild, function(obj) {
return obj.Fullname === rowData.Fullname;});
var div = $('<table/>');
div.DataTable( {"paging": false,
"ordering": true,
"info": false,
"data": file,
"columns": [
{ "title": "Fullname", "data": "Fullname" },
{ "title": "Date","data": "Date" },
{ "title": "Day","data": "Day" },
{ "title": "Logged_Hours","data": "Logged_Hours" },
{ "title": "Present_Hours","data": "Present_Hours" }],
"order": [[1, 'asc']]})
return div;
}
// Add event listener for opening and closing details
$('#example tbody').on('click', 'td.details-control', function () {
var tr = $(this).closest('tr');
var row = table.row( tr );
if ( row.child.isShown() ) {
// This row is already open - close it
row.child.hide();
tr.removeClass('shown');
}
else {
// Open this row
row.child( format(row.data()) ).show();
tr.addClass('shown');
}
} );
});
};
function getMonth(){
$(document).ready(function() {
var month_yr = $('#recent').val();
$("#AjaxLoader").show();
$.getJSON('/attendance_log' + '/' + month_yr,
function(data) {
var tabledata = data.Main,
tableChild = data.Child,
Expected_hrs = data.Expected_hrs,
Hours_logged = data.Hours_logged,
Working_days = data.Working_days;
table_month = data.table_month;
console.log(tabledata);
/* Formatting function for row details - modify as you need */
document.getElementById("table_name").innerHTML = "Attendance log for " + table_month + " Month";
$("#AjaxLoader").hide();
ts_data(tabledata,tableChild,Expected_hrs,Hours_logged,Working_days,table_month);
});
})
}
var startDate = new Date();
$('.from').datepicker({
autoclose: true,
minViewMode: 1,
format: 'mm-yyyy'
}).on('changeDate', function(selected){
startDate = new Date(selected.date.valueOf());
startDate.setDate(startDate.getDate(new Date(selected.date.valueOf())));
$('.to').datepicker('setStartDate', startDate);
});
window.onload = function(){
var today = new Date().toISOString().substr(0, 10);
var month_yr = today.substring(5, 7) +"-" + today.substring(0,4);
document.getElementById("recent").setAttribute("value", month_yr);
getMonth()
};

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.

dataTable page length change issue

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;
}

Categories