Conditional checking of "datatable checkboxes" in jQuery - javascript

Hi I'm trying to create a table that consists of checkboxes. And each row has its own class and ID.
$('#niisPrprtyCoverageTable').dataTable({
"data" : coverageList,
"columns" : [ {
"data" : "seqNo",
"visible" : false
}, {
"data" : "coverageCode"
}, {
"data" : "coverageName"
}, {
"data" : "coverageCode",
"width" : "80px",
"className" : "text-center",
render : function(data, type, row) {
var arrData = data.split(";");
var coverageCd = arrData[0];
var coverageRel = nvl(arrData[1], coverageCd);
data = '<input class="'+coverageRel+'" id="'+coverageCd+'" type="checkbox" onClick="addToArray('
+ coverageCd
+ ','
+ coverageRel
+ ')">';
return data;
}
} ],
"searching" : false,
"bLengthChange" : false,
"iDisplayLength" : 15 ,
"bSort" : false,
"columnDefs" : [ {
"targets" : [ 1, 2 ],
"className" : "left"
}, {
"targets" : [ 2 ],
"width" : "150px",
}, {
"targets" : [ 1 ],
"width" : "100px",
}, {
"targets" : [ 3 ],
"width" : "50px",
"className" : "text-center"
} ]
});
niisPrptyCoverageTable = $('#niisPrprtyCoverageTable').DataTable();
$('#select-all').on('click', function(){
alert('ss');
// Get all rows with search applied
var rows = niisPrptyCoverageTable.rows({ 'search': 'applied' }).nodes();
// Check/uncheck checkboxes for all rows in the table
$('input[type="checkbox"]', rows).prop('checked', this.checked);
});
What should happen is, if I check the main row, all the rows under his 'code or id' should be checked also.
It works but only on the first page
but doesn't work on the second page of the datatable
var array = [];
function addToArray(coverageCd, coverageRel) {
var rows = niisPrptyCoverageTable.rows('.'+coverageRel).nodes().className;
$('input[class='+coverageCd+']', rows).prop('checked', '#'+coverageCd.checked);
}

Use $() API method to get access to elements on all pages, not just current page.
For example:
var array = [];
function addToArray(coverageCd, coverageRel) {
var rows = niisPrptyCoverageTable.rows('.'+coverageRel).nodes().className;
niisPrptyCoverageTable.$('input[class='+coverageCd+']', rows).prop('checked', '#'+coverageCd.checked);
}
Alternatively see jQuery DataTables Checkboxes extension for easier handling of checkboxes in a table powered by jQuery DataTables.

Related

Add link to Ajax sourced data in jQuery Datatables

I want to add a link/href to the 2nd column (the one with "C" data in it). I have tried the columns render function but it only has data of the current column.
https://datatables.net/reference/option/columns.render
I want to use data from different columns onto anchor tag of column 2
this guy here
https://stackoverflow.com/a/47696609/11575565
explains using rowID which would've solved my problem but this isnt working.
I tried using $.getJSON and append() over ajax function but it doesnt work as well.
$(document).ready(function() {
var table = $('#bla').DataTable({
"ajax" : "blist.json",
"columns" : [
{ "data" : null,defaultContent: "-" },
{ "data" : "C" },
{ "data" : "B" },
{ "data" : "D" },
{ "data" : null,defaultContent: "-" },
{ "data" : null,defaultContent: "-" },
],
[the array in blist.json has data "A","B","C","D","E"]
Say, your Link value is in key E then, you would be able to use render as shown below.
"columns" : [
{ "data" : null,defaultContent: "-" },
{ "data" : "C",
"render": function(data, type, row, meta){
if(type === 'display'){
data = '' + data + '';
}
return data;
}
},
{ "data" : "B" },
{ "data" : "D" },
{ "data" : null,defaultContent: "-" },
{ "data" : null,defaultContent: "-" },
]

JS - jQuery.fn.DataTable is undefined

I'm trying to use datatables to display a list of records in two different pages.
Problem is the first datatable works while the second one (that's a perfect clone of the first) doesn't...
The issue is related to $.fn.DataTable: in the first case it exists so the script goes on filling the datatable while in the second case it is undefined.
The "big" problem here is that both the datatables are perfectly the same. What changes are the ids and the content...
These are the two scripts I'm using to populate the datatables:
transactionsHistoryInit : function($) {
var datatable = $('#transactions-history-table');
if (datatable.length > 0 && typeof $.fn.DataTable !== "undefined") {
datatable.DataTable({
"responsive" : true,
"searching" : false,
"processing" : true,
"serverSide" : true,
"pageLength" : 20,
"lengthChange" : false,
"stateSave" : true,
"pagingType" : "full_numbers",
"info" : false,
"columnDefs" : [ {
"orderable" : false,
"targets" : [ 1, 2, 3, 4 ]
} ],
"ajax" : {
"url" : siteData.ajaxurl + "?action=transactions_history",
"type" : 'POST'
},
"language" : {
"url" : siteData.ajaxurl
+ "?action=datatable_internazionalization"
}
});
transactionStartDate.datetimepicker({
"locale" : transactionStartDate.data("locale")
});
transactionEndDate.datetimepicker({
"locale" : transactionEndDate.data("locale"),
"defaultDate" : new Date()
});
transactionStartDate.add(transactionEndDate).on("dp.change",
function(e) {
datatable.draw();
});
}
},
bankToBankAccountChoice : function($) {
var datatable = $('#bank-account-table');
if (datatable.length > 0 && typeof $.fn.DataTable !== "undefined") {
datatable.DataTable({
"responsive" : true,
"searching" : false,
"processing" : true,
"serverSide" : true,
"pageLength" : 10,
"lengthChange" : false,
"stateSave" : true,
"pagingType" : "full_numbers",
"info" : false,
"ajax" : {
"url" : siteData.ajaxurl
+ "?action=bank_to_bank_account_choice",
"type" : 'POST'
},
"language" : {
"url" : siteData.ajaxurl
+ "?action=datatable_internazionalization"
}
});
}
}
I was also getting $.fn.dataTable as undefined
In my case, I was loading jquery multiple times. Jquery must be loaded only once.

How to remove selected existing data and add new row without affecting other rows in Jquery data table

I have 100 rows of data, i want to remove selected data based on ID and add new row for that ID. I want to edit the rows based on ID.
Here is my code:
oCustomization : {
sExportFunctionCall : oMapUrls.exportLiveFleetReport,
bAdvanceExport : true,
bShowDefaultAll : !bLivePaginate
},
pageLength : !bLivePaginate ? -1 : Global.rowLength,
scrollCollapse : false,
scrollY : iDataTableHeight,
serverSide : bLivePaginate,
order : [ [ 3, "desc" ] ],
columns : [
{
"data" : "trackeeName",
"width" : aColumnWidths[0],
"class" : "no-word-break",
"settings" : {
source : function(request, oCallback) {
oCallback($.ui.autocomplete.filter(Global.aJSTreeVehicleItems || [], request.term));
}
},
"render" : function(value, type, rowData) {
//Some code here
}
},
{
"data" : "firstName",
"width" : aColumnWidths[1],
"class" : "no-word-break",
settings : {
source : Global.getDriverSuggestion
},
"title" : jQuery.i18n.prop("driver.title.txtInfo"),
"visible" : Global['show.driver.in.reports'] == 1,
"render" : function(value, type, rowData) {
return getUserName(rowData.firstName, rowData.lastName);
}
},
{
"data" : "groupName",
"width" : aColumnWidths[2],
"class" : "no-word-break",
"settings" : {
source : function(request, oCallback) {
oCallback($.ui.autocomplete.filter(Global.aJSTreeGroupItems || [], request.term));
}
},
"title" : jQuery.i18n.prop("vehicle.col2label")
},
{
"data" : "dateAndTime",
"width" : aColumnWidths[3],
"searchable" : !bLivePaginate,
"class" : "wordBreak",
"title" : jQuery.i18n.prop("report.columnTitle.date"),
"render" : function(value, type, rowData) {
if (type == "display") {
return rowData.formattedDate;
}
return value;
}
}
I get data in JSON format. I want to remove selected rows , it should not affect other rows data.
Simply use WHERE
DELETE FROM DBNAME WHERE ID=XXX
then Insert into the table with that ID
however, if you want to delete and insert together always, an UPDATE query will work better

How to get the selected value from Kendo UI grid

I am using Kendo grid. I want to get the value(field-nlv_id) for the multiple row selected if select the rows. Also i want to get the number of selected rows and pass to the controller. Let me know the way to do it.
columns : [
{
'field' : 'nlv_id',
'title' : 'Asset ID'
},
{
'field' : 'due_date',
'title' : 'Partner Due Date'
},
{
'field' : 'link',
'title' : 'Partner'
},
{
'field' : 'playlist_type',
'title' : 'Playlist Style'
},
{
'field' : 'show_code',
'title' : 'Show Code'
},
{
'field' : 'status',
'title' : 'Status'
},
{
'field' : 'retry_count',
'title' : '# Retries'
}
],
scrollable : false,
pageable : {
pageSizes : [ 10, 25, 50 ],
buttonCount : 5,
refresh : true,
messages : {
display : "{0} - {1} of {2} assets",
itemsPerPage : "assets per page",
empty : "No assets to display"
}
},
dataSource : new kendo.data.DataSource({
serverPaging : true,
transport : {
read : getJobs
},
pageSize : 10,
schema : {
total : returnTotalCount
}
}),
selectable : 'multiple',
sortable : true
};
You will need to do an change() event on grid, then you will have selected items, for convinience i did an example using an list with all selected items, so you can easily get numbers of rows selected.
change: function (e, args) {
var currentSelected = this.select();
var dataSource = $grid.dataSource.data();
currentItems = [];
$.map(currentSelected, function (item) {
currentItems.push($grid.dataItem(item).nlv_id) ;
return $grid.dataItem(item).nlv_id;
});
alert(currentItems);
},
You can get count like that
currentItems.length;
EDIT: For convinience i create an example to do, is easier.
Important: you must set you 'nlv_id' in Schema!
http://jsfiddle.net/2ojwwpLf/
hope this help

datatables ajax reload from new source

How do I reload datatables with the new ajax functionality?
I think it's a problem of scope.
function load_table(tableName,src)
{
var oTable = $('#'+tableName).DataTable({
'bProcessing' : true,
'bServerSide' : true,
'responsive' : true,
'sAjaxSource' : src,
'fnServerData' : function(sSource, aoData, fnCallback)
{
$.ajax({
'dataType': 'json',
'type' : 'POST',
'url' : sSource,
'data' : aoData,
'success' : fnCallback
});
},
});
}
Try to reload it from a different data source:
$("input[type="button"]").on('click',function()
{
oTable.ajax.url( 'newsource' ).load();
alert( 'Data source: '+oTable.ajax.url() );
});
Alert outputs : src : newsource
Browser loads table from src: oldsource
I've had the same issue to anyone who runs into this problem in the future here is the solution:
To accomplish reloading of data from a different source:
refer to the DOM table element NOT the DataTable object or you will get a reinitilization error:
step 1: clear data :
$('#your_table_name').DataTable().clear();
step 2: Destroy the DataTable object
$('#your_table_name').DataTable().destroy();
if you're using child rows this is very important remove the click listener
$( "#your_table_name tbody" )
.off( "click", "td.details-control");
Reinit DataTables:
loadTable('newsource','your_table_name')
and your loadTable function
function loadTable(src,tableName)
{
var oTable = $('#'+tableName).DataTable({
'bProcessing' : true,
'bServerSide' : true,
'responsive' : true,
"sDom": '<"toolbar"lfr>tip<"F">R',
'sAjaxSource' : src,
});
//initchildrows()
}
Yes, this seems to be a scope problem. You assign the dataTables instance to a local variable :
function load_table(tableName,src)
{
var oTable = $('#'+tableName).DataTable({
'bProcessing' : true,
...
assign it to a global variable instead :
var oTable;
function load_table(tableName,src)
{
oTable = $('#'+tableName).DataTable({
'bProcessing' : true,
...
If it still not works - but it should, you are using oTable.ajax.url(<src>).load() just right - then simply reinitialise the table with the destroy : true option :
var oTable;
function load_table(tableName,src)
{
oTable = $('#'+tableName).DataTable({
destroy : true,
'bProcessing' : true,
...
and call load_table from the event :
$("input[type='button']").on('click',function()
{
load_table('tableName', 'newsource');
});
Thanks,Here is my solution,it is not perfect,must send twice url,thanks to this author: How do I modify ajax url of a query datatable? eg: if you If you initialize datatable like this:
var datatables_options = {
"aLengthMenu" : [ [ 5, 10, 50, 100,500, -1 ],[ 5, 10, 50, 100,500, "All" ] ],
"iDisplayLength" : 5,
"sDom": 'T<"clear">rt<"float_left"i><"float_right_nexpage"p><"float_right_display"l>',
<'float_right_nexpage'p> <'float_right_display'l>>",
"bSort" : false,
"bProcessing" : false,
"bServerSide" : true,
"bStateSave" : true,
"bDestroy" : true,
"bDeferRender":true,
"bJQueryUI" : false,
"sScrollX" : "100%",
"bStateSave":true,
"language" : oLanguageData,
"aoColumns" : aoColumnsData,
"fnDrawCallback" : function() {
//Checkbox status updates
$("#uniform-check-all").removeClass("checker");
$("span").removeClass("checked");
$("span #check-all").attr("checked",false);
$.uniform.update();
},
"fnRowCallback" : function(nRow, aData,
iDataIndex) {
},
"sAjaxSource" : "wageQuery.action?wageDate="
+ date,
"fnServerData" : function(sSource, aoData,
fnCallback) {
$.ajax({
"type" : 'post',
"async":false,
"url" : sSource,
"dataType" : "json",
"data" : aoData,
"success" : function(resp) {
fnCallback(resp);
}
});
},
"fixedColumns": {
"iLeftColumns" : 4,
"sHeightMatch" : "auto"
},
};
import: if you want to reload new url(action),here is the solution: first step: Initialize table variables at the JSP file,like this:
<script type="text/javascript">
var wageNowTable;//Table global variables, do not put in the ready function, otherwise it is not a global variable
</script>
second step: Add the following code to the JS file,like this:
$("#wages-query")
.click(
function() {
var datatables_options = {
"aLengthMenu" : [ [ 5, 10, 50, 100,500, -1 ],[ 5, 10, 50, 100,500, "All" ] ],
"iDisplayLength" : 5,
//The following SDOM, 1.9 version will not show up
"sDom": 'T<"clear">rt<"float_left"i><"float_right_nexpage"p><"float_right_display"l>',
//"sDom" : "<r>t<'float_left'i><'float_right_nexpage'p><'float_right_display'l>>",
"bSort" : false,
"bProcessing" : false,
"bServerSide" : true,
"bStateSave" : true,
"bDestroy" : true,
"bDeferRender":true,
"bJQueryUI" : false,
"sScrollX" : "100%",
"bStateSave":true,
"language" : oLanguageData,
// "aaData" : data,
"aoColumns" : aoColumnsData,
"fnRowCallback" : function(nRow, aData,
iDataIndex) {
},
"sAjaxSource" : "wageQuery.action?wageDate="
+ date,
"fnServerData" : function(sSource, aoData,
fnCallback) {
$.ajax({
"type" : 'post',
"async":false,
"url" : sSource,
"dataType" : "json",
"data" : aoData,
"success" : function(resp) {
fnCallback(resp);
}
});
},
"fixedColumns": {
"iLeftColumns" : 4,
"sHeightMatch" : "auto"
},
};
//Determine whether the table has been an instance, there is no instance, has been a direct update, load the corresponding URL
if (typeof(wageNowTable) == "undefined") {
wageNowTable = $('#sample_1').dataTable(datatables_options);
}else{
var oSettings = wageNowTable.fnSettings();
oSettings.sAjaxSource = "wageQuery.action?wageDate="
+ date;
wageNowTable.fnDraw(false);//Don't jump to the first page, the page number and the reserved page displays the number of
wageNowTable.fnDraw(false);//
}
//Important point: listen to the state of the check box, the important need to use the form of on, the direct click can not change the state
$('.DTFC_LeftHeadWrapper div').on('click','input' ,function () {
$("#uniform-check-all").removeClass("checker");
$("span").removeClass("checked");
var val = $(this).prop("checked");
$("input[type='checkbox']", ".DTFC_LeftHeadWrapper").attr("checked", val);
$("#check-all").attr("checked", val);
if (val) {
$(".checkboxes").each(function(index){
$(this).attr("checked", val);
});
} else {
$(".checkboxes").each(function(index){
$(this).attr("checked", val);
});
}
} );
});
Determine whether the table has been an instance, there is no instance, has been a direct update, load the new URL:
if (typeof(wageNowTable) == "undefined") {
wageNowTable = $('#sample_1').dataTable(datatables_options);
}else{
var oSettings = wageNowTable.fnSettings();
oSettings.sAjaxSource = "wageQuery.action?wageDate="
+ date;
//need twice fndraw
wageNowTable.fnDraw(false);
wageNowTable.fnDraw(false);
}

Categories