Jquery Datatables Selected Checkbox to Input Field - javascript

I have here a Datatable with 3 columns: Checkbox, Name, and SSNTIN, when I select rows then click Submit, their SSNTIN will output in '#txtSSNTIN' input field like "1001,1002,1003" but my problem is only the selected rows in the current page of my Datatable are being outputted in the input field, when I go to another page there is an indicator that the other rows from the previous page are still selected but only current page is outputting, please help
Datatable
Namestable = $('#NamesDatatable').DataTable({
'select': {
'style': 'multi',
},
'columnDefs': [{
'targets': 0,
'searchable': false,
'orderable': false,
'render': function (data, type, full, meta) {
return '<input type="checkbox" name="id[]" value="'+data.ssn_or_tin+'">';
}
}],
'order': [[1, 'asc']],
"ajax": {
"url": '/Home/GetAllCusname',
"type": "POST",
"datatype": "json",
"data": function (d) {
d.searchParameters = {};
d.searchParameters.name = $('#txtName').val();
}
},
"columns": [
{
data: null,
defaultContent: '',
},
{ "data": "name", "autoWidth": true },
{ "data": "ssn_or_tin", "autoWidth": true }
]
});
Submit Button
$('#btnSubmit').on("click", function (e) {
e.preventDefault();
var searchNames = $('input:checkbox:checked').map(function () {
return $(this).val();
}).get();
$('#txtSSNTIN').val(searchNames);
});

Related

Datatables.net MVC JavaScript Populated table erroneously shows Showing 0 to 0 of 0 entries

First time using DataTables.net with MVC and JavaScript. On my .cshtml page I have a Datatables.net table that correctly brings back data and populates the table using JavaScript. (I have copied this from another example that also brings back data correctly and populates the table.) My problem is that at the bottom of the table it erroneously shows Showing 0 to 0 of 0 entries despite displaying multiple rows of information. (on the example that I copied from it correctly shows 1 of 20 entries).
My code below:
<script type="text/javascript">
function getTransactionListingHistory(contactCode) {
var groupColumn = 1;
if ($.fn.dataTable.isDataTable('#datatableTransactionHistory')) {
table = $('#datatableTransactionHistory').DataTable();
table.destroy();
}
var historyTable = $('#datatableTransactionHistory').DataTable({
order: [0, "desc"],
"processing": true,
"serverSide": true,
"filter": false,
"ajax": {
"url": "/Transactions/TransactionsGetData?contactCode=" + contactCode,
"type": "POST",
"datatype": "json"
},
columnDefs: [
//{ "targets": [1], "visible": false, "searchable": false }
],
"columns": [
{
"data": "lineDate", "name": "LineDate", "autoWidth": true,
},
{
"data": "lineReference", "name": "lineReference", "autoWidth": true,
"render": function(data, type, row) {
return data;
}
},
{
"data": "formattedDebitAmount", "autoWidth": true, "defaultContent": "",
"render": function(data, type, row) {
if (data != null) {
return "<a class='text-danger text-right text-nowrap'>" + data + "</a>";
}
}
},
{
"data": "LineID", "name": "lineID", "autoWidth": true,
"render": function(data, type, row)
{
return '<a onclick="repeatTransaction(' + '\'' + row.lineID + '\');" href="#" id="repeat-link"><img src="' + "/images/icons/refresh.svg" + '" /> ' + 'Repeat' + '</a>';
}
},
],
fixedHeader: true,
"aLengthMenu": [[10, 25, 50, 100, 250, 500], [10, 25, 50, 100, 250, 500]],
"iDisplayLength": #myPagingSize,
language: {
processing: "<div style='color: #ff6611!important;' class='spinner-border text-warning m-2' role='status' aria-hidden='true'></div> Processing ...",
paginate: {
next: '<i class="fas fa-arrow-right"></i>',
previous: '<i class="fas fa-arrow-left"></i>'
}
}
});
$('#datatableTransactionHistoryul.pagination').addClass("pagination-rounded");
};
</script>

Data table not working and not filter data

I have used data table code, but where I used search filter table getting code error.
if($("#newuser").length != 0) {
var oTable = $("#newuser").DataTable({
"processing": true,
"serverSide": true,
"ajax": {
"url": base_url+'users/listing',
"type": "POST",
},
"columnDefs": [{ orderable: false, targets: [0] }],
"order": [[6, "desc" ]],
});
$('#newuser').on( 'draw.dt', function () {
$('[data-plugin="switchery"]').each(function (idx, obj) {
new Switchery($(this)[0], $(this).data());
});
});
}
change this part
"url": base_url+'users/listing',
into this
"url": "<?php echo base_url('users/listing'); ?>",
***do not forget that base_url is from PHP

Hide a button in jquery based on user access

I'm trying to hide a button. If it was on the html i would simply do
<security:authorize access="hasAuthority('Administrator')">
//html button code
</security:authorize>
but my delete button is being generated from datatable.
var table = $('#dataTable').DataTable({
language: {
searchPlaceholder: "Search...",
emptyTable: "There are no available flows."
},
columnDefs: [ {
orderable: false,
className: 'select-checkbox',
targets: 0
},
{type: "date-euro", targets: 7},
{type: "date-euro", targets: 8}
],
order: [[1, 'desc']],
select: {
style: 'multi',
selector: 'td:first-child'
},
lengthChange: false,
dom: 'Bfrtip',
buttons: [
{
text: '<span class="fa fa-plus"></span> Create',
className: 'btn-primary-outline',
action: function () {
location.href = "create-flow";
}
},
{
text: '<span class="fa fa-trash"></span> Delete',
className: 'btn-danger-outline',
action: function () {
console.log($('#hasAuthority').val());
var selectedRows = table.rows({selected: true});
if (selectedRows.nodes().length > 0) {
//Get names
var data = selectedRows.data();
var names = [];
$.each(data, function (index, value) {
names.push(value[2]);
});
//Remove them
$.ajax({
url: '/flow/delete?names=' + names,
type: 'delete',
success: function () {
//reload page
location.reload();
}
});
//de-select selected rows
table.rows('.selected').deselect();
}
}
}
]
});
I'm trying to give a value to a input if user is admin or not but I'm getting undefined
<security:authorize access="hasAuthority('Administrator')" var="hasAuthority"></security:authorize>
<input type="hidden" id="hasAuthority" value="${hasAuthority}">
But then how do I corporate the if(hasAuthority) only on the delete button? The syntax doesn't match.

How to manage datatable for large data

I have a datatable for report. When i tried to show my datas, My browser freezed or crashed. My js code on below
Reporting_Report.DTReport = $('#Report-ReportTable').DataTable({
"ajax": {
"url": "/Ajax/JsonProvider?Method=HardwareHostScreenUsage&GenericObject=true&Json=" + JSON.stringify(json),
"dataSrc": ""
},
"columns": [
{
"data": "BranchName",
"sTitle": "BranchName"
},
{
"data": "HardwareHostFriendlyName",
"sTitle": "Hardware Host Friendly Name"
},
{
"data": "HardwareHostScreenUsageScreenState",
"defaultContent": "N/A",
"sTitle": "Hardware Host Screen Name"
"render": function(data, type, full) {
if (data && Util.Check.IsInteger(data)) {
if (data == 1) {
return "Sorry Screen";
} else if (data == 2) {
return "Welcome Screen";
} else if (data == 3) {
return "Progress Screen";
}
}
}
},
{
"data": "HardwareHostScreenUsageSecondOnScreen",
"sTitle": "Elapsed Time On Hardware Host Screen"
},
{
"data": "HardwareHostScreenUsageRecordDate",
"sTitle": "Hardware Host Screen Usage Record Date"
"render": function (data, type, full) {
return Util.JsonDateToDate(data).format("dd.mm.yyyy HH:MM:ss");
}
}
],
"pageLength": 20,
"lengthMenu": [
[20, 50, 100, -1],
[20, 50, 100, "All"]
],
"info": false,
bFilter: true,
bInfo: false,
"order": [[0, "asc"]],
"scrollX": true,
dom: 'Bfrtip',
buttons: [
{
extend: 'copy'
},
{
extend: 'csv'
},
{
extend: 'excel'
},
{
extend: 'pdf',
title: "Detailed Ticket Report"
message: startDate + " " + startTime + " - " + endDate + " " + endTime + "\t" + datetime,
pageSize: 'LEGAL'
},
{
extend: 'print'
}
]
});
I have more than 100.000 datas.
I thinked maybe i can just get showing page datas and total data number(for manage page numbers) and when clicked another page number send new query and get new datas. But i couldn't find how to do that to.(maybe it cause some another problems (shorting, searching vs.)
Have you got any ideas and solutions.(or this problem has already a solution)
footnote:json has some filters for query(time, branch, etc.)
HardwareHostScreenUsage method gets my datas on c# side.
you can use client side data source also-
var mydata = [];
$('#example').DataTable({
data: data,
deferRender: true,
scrollY: 200,
scrollCollapse: true,
scroller: true
});
fetch all data at once from server and show it while scrolling the table .
You Need these library -
https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js
https://cdn.datatables.net/scroller/1.4.3/js/dataTables.scroller.min.js

jQuery datatable retain row highlight after reload

I am reloading my datatable on 10 second intervals. When a user clicks on a row, that row will highlight. But when the datatable reloads, the highlight is gone.
Here is the shortened code for my datable:
$(document).ready(function()
{
// set datatable
$('#example1').DataTable({
"ajax": {
"url": "api/process.php",
"type": "POST",
"dataSrc": ''
},
"columns": [
{ "data": "" },
{ "data": "column1" },
{ "data": "column2" },
{ "data": "column3" }
],
"iDisplayLength": 25,
"order": [[ 6, "desc" ]],
"scrollY": 600,
"scrollX": true,
"bDestroy": true,
"stateSave": true
});
// reload datatable every 30 seconds
setInterval(function()
{
var table = $('#example1').DataTable();
table.ajax.reload();
}, 30000);
// highlight row
$('#example1 tbody').on('click', 'tr', function()
{
$('#example1 tbody > tr').removeClass('selected');
$(this).addClass('selected');
});
});
All of the above works exactly how it's supposed to work. I just need to retain the row highlight after the datatable reloads.
Also, I attempted the answer from this post, but I scrapped it as the row no longer highlights.
Kindly update js file with below changes. Below code will save row clicked in global parameter and then focus the clicked row after ajax call.
var gblIndex = 0; //this will save row clicked index
function setFocus(){
$($('#example1 tbody > tr')[gblIndex]).addClass('selected');
}
$(document).ready(function()
{
// set datatable
$('#example1').DataTable({
"ajax": {
"url": "api/process.php",
"type": "POST",
"dataSrc": ''
},
"columns": [
{ "data": "" },
{ "data": "column1" },
{ "data": "column2" },
{ "data": "column3" }
],
"iDisplayLength": 25,
"order": [[ 6, "desc" ]],
"scrollY": 600,
"scrollX": true,
"bDestroy": true,
"stateSave": true
});
// reload datatable every 30 seconds
setInterval(function()
{
var table = $('#example1').DataTable();
table.ajax.reload();
setFocus(); // this will set focus/highlight row
}, 30000);
// highlight row
$('#example1 tbody').on('click', 'tr', function()
{
$('#example1 tbody > tr').removeClass('selected');
$(this).addClass('selected');
gblIndex = $(this).index(); // this will save the index clicked
});
});
You should review their actual selection documentation to manipulate this. This feature is already built in and setup so on ajax.reload() it will keep your selections.
You can apply classes/styling with their methods as well.
https://datatables.net/reference/option/#select

Categories