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.
Related
I have a simple collection events
{
"_id" : ObjectId("5e2a9bb9dcb646448f9409b3"),
"year" : 2020,
"employee_id" : "5e1afe5ab7bad92b20365476",
"event" : ["Holidays"],
"total" : 21,
"used" : 1
}
and i don't want to be able to delete the documents that have used field grater than 0.
I use this
db.collection('events').deleteOne({_id: ObjectId("5e2a9bb9dcb646448f9409b3"), used: 0});
Do i need to set an index on used field if i already use _id?
Thanks
Not necessary. MongoDB already uses _id (unique index created by MongoDB) to delete documents.
db.collection('events').find({_id: ObjectId("5e2a9bb9dcb646448f9409b3"), used: 0}).explain();
"winningPlan" : {
"stage" : "FETCH",
"filter" : {
"used" : {
"$eq" : 0.0
}
},
"inputStage" : {
"stage" : "IXSCAN",
"keyPattern" : {
"_id" : 1
},
"indexName" : "_id_",
"isMultiKey" : false,
"multiKeyPaths" : {
"_id" : []
},
"isUnique" : true,
"isSparse" : false,
"isPartial" : false,
"indexVersion" : 2,
"direction" : "forward",
"indexBounds" : {
"_id" : [
"[ObjectId('5e2a9bb9dcb646448f9409b3'), ObjectId('5e2a9bb9dcb646448f9409b3')]"
]
}
}
}
I have managed to get my recurring events to show up on the calendar, but my single allDay events will not render and I believe its a field problem.
I've tried making the event's start time an iso date which doesn't seem to matter as my recurring events are being saved as a string.
This is a recurring event and shows up on the calendar
{
"_id" : ObjectId("5d4af079f91ff532f8fc0385"),
"daysOfWeek" : [
1,
2,
3
],
"locationId" : ObjectId("5d28cad23f49646797e05adc"),
"allDay" : true,
"start" : "2019-08-07",
"end" : "2019-08-07",
"startRecur" : "2019-08-07",
"endRecur" : "2019-08-31",
"title" : "Change Bulbs",
"backgroundColor" : "rgb(87, 87, 244)",
"source" : null,
"interval" : "Weekly",
"category" : "Facility",
"monday" : true,
"tuesday" : true,
"wednesday" : true,
"completed" : false,
"frequency" : null,
"__v" : 0
}
this is a single event that showed up in FC-v3 but wont in v4
{
"_id" : ObjectId("5d4b455e121f726f510f2b5c"),
"daysOfWeek" : [],
"batchId" : ObjectId("5d28f52d823083adfc6e8c4d"),
"locationId" : ObjectId("5d28cad23f49646797e05adc"),
"end" : null,
"startRecur" : "",
"endRecur" : "",
"allDay" : true,
"start" : "2019-08-08",
"title" : "First Transplant",
"backgroundColor" : "rgb(87, 87, 244)",
"interval" : "Single Event",
"category" : "Cultivation",
"monday" : false,
"tuesday" : false,
"wednesday" : false,
"thursday" : false,
"friday" : false,
"saturday" : false,
"sunday" : false,
"completed" : false,
"__v" : 0
}
so i made an event with the proper ISO Date and it failed as well
{
"_id" : ObjectId("5d4b4f9a56114f747c7ddcef"),
"daysOfWeek" : [],
"batchId" : ObjectId("5d28f52d823083adfc6e8c4d"),
"locationId" : ObjectId("5d28cad23f49646797e05adc"),
"allDay" : true,
"start" : ISODate("2019-08-08T00:00:00.000Z"),
"end" : null,
"title" : "IMP",
"backgroundColor" : "rgb(87, 87, 244)",
"interval" : "Single Event",
"category" : "Cultivation",
"monday" : false,
"tuesday" : false,
"wednesday" : false,
"thursday" : false,
"friday" : false,
"saturday" : false,
"sunday" : false,
"completed" : false,
"__v" : 0
}
comp.ts code
createEvent(form) {
if (form.valid) {
this.newEvent.category = 'Cultivation';
this.newEvent.completed = false;
this.newEvent.allDay = true;
this.newEvent.locationId = this.selectedLocation._id;
this.newEvent.batchId = this.selectedBatch._id;
this.newEvent.start = moment(this.newEvent.start).utc();
this.newEvent.start.hours(0).minutes(0).seconds(0);
// this.newEvent.source = null;
// this.newEvent.daysOfWeek = [];
if (this.newEvent.interval === 'Single Event') {
this.newEvent.end = null;
// this.newEvent.startRecur = '';
// this.newEvent.endRecur = '';
this.newEvent.monday = false;
this.newEvent.tuesday = false;
this.newEvent.wednesday = false;
this.newEvent.thursday = false;
this.newEvent.friday = false;
this.newEvent.saturday = false;
this.newEvent.sunday = false;
}
// if ( this.newEvent.interval === 'Daily' || this.newEvent.interval === 'Weekly'){
// }
if (this.newEvent.interval === 'Weekly') {
this.newEvent.startRecur = this.newEvent.start;
this.newEvent.end = this.newEvent.start;
this.newEvent.frequency = NaN;
if (this.newEvent.sunday) {
this.newEvent.daysOfWeek.push(0);
}
if (this.newEvent.monday) {
this.newEvent.daysOfWeek.push(1);
}
if (this.newEvent.tuesday) {
this.newEvent.daysOfWeek.push(2);
}
if (this.newEvent.wednesday) {
this.newEvent.daysOfWeek.push(3);
}
if (this.newEvent.thursday) {
this.newEvent.daysOfWeek.push(4);
}
if (this.newEvent.friday) {
this.newEvent.daysOfWeek.push(5);
}
if (this.newEvent.saturday) {
this.newEvent.daysOfWeek.push(6);
}
}
...sub to database
setting "daysOfWeek" : [], means that you are telling the calendar it cannot show the event on any day of the week. That's why it won't appear.
Simply don't set that option in your code for single events, and it will be fine:
{
"_id" : ObjectId("5d4b455e121f726f510f2b5c"),
"batchId" : ObjectId("5d28f52d823083adfc6e8c4d"),
"locationId" : ObjectId("5d28cad23f49646797e05adc"),
"end" : null,
"startRecur" : "",
"endRecur" : "",
"allDay" : true,
"start" : "2019-08-08",
"title" : "First Transplant",
"backgroundColor" : "rgb(87, 87, 244)",
"interval" : "Single Event",
"category" : "Cultivation",
"monday" : false,
"tuesday" : false,
"wednesday" : false,
"thursday" : false,
"friday" : false,
"saturday" : false,
"sunday" : false,
"completed" : false,
"__v" : 0
}
Demo: https://codepen.io/ADyson82/pen/LwdgeG
P.S. There's nothing wrong with your date string.
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.
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 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);
}