Datatables initialization warning - javascript

I have a dropdown with multiple options that initializes a datatable using javascript. Everything works fine but the problem comes during execution in which when the option is selected second time i get an error , check out this fiddle,
DataTables warning (table id = 'defDiv'): Cannot reinitialise DataTable.
And Below is my code :
if(user.position=="DEF"){
var table = $('#defDiv').DataTable({
"aaData":defenders,
"iDisplayLength":15,
"aoColumns": [
{ "mDataProp": "playerInfo" },
{ "mDataProp": "playerName" },
{ "mDataProp": "playerClub" },
{ "mDataProp": "playerValue" },
{ "mDataProp": "playerPoints" },
],
"order": [[ 3, "desc" ]],
});
}
Question is how can i prevent the warning from happening when the option is selected again ?

I've altered you code and it works now:
var goalkepeers = [{
"playerName": "Mignolet",
"playerClub": "Liverpool",
"playerValue": "5.0",
"playerPoints": "89",
}, {
"playerName": "de Gea",
"playerClub": "Manchester",
"playerValue": "6.7",
"playerPoints": "120",
}];
var defenders = [{
"playerName": "Ivanovic",
"playerClub": "Chelsea",
"playerValue": "7.8",
"playerPoints": "100",
}, {
"playerName": "Mertesacker",
"playerClub": "Arsenal",
"playerValue": "7.7",
"playerPoints": "110",
}];
var aoColumns = [{
"sTitle": "Name",
"mDataProp": "playerName"
},{
"sTitle": "Club",
"mDataProp": "playerClub"
},{
"sTitle": "Value",
"mDataProp": "playerValue"
},{
"sTitle": "Points",
"mDataProp": "playerPoints"
}];
var table = null;
$("#playersFilter").change(function () {
var value = $('#playersFilter').val();
if (value == "gk") {
if ($.fn.dataTable.isDataTable('#players')) {
$('#players').DataTable().destroy();
}
table = $('#players').DataTable({
"aaData": goalkepeers,
"iDisplayLength": 15,
"aoColumns": aoColumns,
"bRetrieve": true,
"order": [
[3, "desc"]
],
"bDestroy": true
});
} else if (value == "def") {
if ($.fn.dataTable.isDataTable('#players')) {
$('#players').DataTable().destroy();
}
table = $('#players').DataTable({
"aaData": defenders,
"iDisplayLength": 15,
"aoColumns": aoColumns,
"bRetrieve": true,
"order": [
[3, "desc"]
],
"bDestroy": true,
});
}
});
I'm pretty sure there's a more efficient way of doing it, I'll have a think and post a link to a JSFiddle as a comment.
You only really need the one table as well:
<select id="playersFilter">
<option>Choose Players</option>
<option value="gk">goalkepeers</option>
<option value="def">Defenders</option>
</select>
<table class="display" id="players"></table>

use this code
if(user.position=="DEF"){
var table = $('#defDiv').DataTable({
"aaData":defenders,
"iDisplayLength":15,
"aoColumns": [
{ "mDataProp": "playerInfo" },
{ "mDataProp": "playerName" },
{ "mDataProp": "playerClub" },
{ "mDataProp": "playerValue" },
{ "mDataProp": "playerPoints" },
],
//EDITS
"bRetrieve":true,
"order": [[ 3, "desc" ]],
// use this in your code
"bDestroy": true,
});
}
this will work for me &
more details

Can you just destroy the table prior to re-initialization?
table.DataTable().destroy();
Something like this:
var table;
if ($.fn.dataTable.isDataTable('#defDiv')) {
table.DataTable().destroy();
}
table = $('#defDiv').DataTable({...
Documentation can be found here
Demo here

Related

internet explorer select dropdown collapse

i have select dropdown which picks no. of pages to be shown as jquery pagination. everything is fine but when it comes to ie. select dropdown collapses.see image.
i also refered link
but it seems it will not work for me.I am doubtful that is it ie default behaviour and can't do much....
<script type="text/javascript">
$(document).ready(function() {
var url="${pageContext.request.contextPath}/aaa/aaa/aaa";
url+="?fromDate=${fromDate}";
url+="&toDate=${toDate}";
url+="&callType=${callType}";
url+="&fullListSize=0";
var table = $('#call_history_detail').DataTable({
"preDrawCallback": function( settings ) {
$("#searchTable").val("");
$('body').modalProgress("show");
},
"drawCallback": function( settings ) {
wordWrap("userName", 80, 2);
$('body').modalProgress("hide");
},
"processing": true,
"serverSide": true,
"searching": false,
//"ajax": url,
"ajax": {
"contentType": "application/json",
"url": url,
"data": function ( d ) {
var drawValue = d.draw;
var length = d.length;
var start = d.start;
var sortCol = d.order[0].column;
var sortType = d.order[0].dir;
return "draw=" + drawValue + "&length=" + length + "&start=" + start + "&sortCol=" + sortCol + "&sortType=" + sortType;
}
},
"oLanguage": {
"sLengthMenu": "Show _MENU_ entries. <img src='${pageContext.request.contextPath}/img/ico_info.png' class='tt'" +
"title='The search function will only search the page you are currently viewing. To do a more expansive search, increase the entries per page. Increasing the entries per page can increase load time.' />"
},
"lengthMenu": [ [25, 50, 100, 500, 1000, 5000], [25, 50, 100, 500, 1000, 5000] ],
"columns": [
{ "name": "userName" },
{ "name": "callType"},
{ "name": "date" },
{ "name": "time" },
{ "name": "from" },
{ "name": "to" },
{ "name": "cost", "width": "10%" },
{ "name": "duration", "width": "10%" }
],
"columnDefs": [
{
"class": "userName",
"data": "userName",
"defaultContent": "",
"targets": 0
},
{
"class": "callType",
"data": "callType",
"defaultContent": "",
"targets": 1
},
{
"class": "date-time",
"data": "timeStart",
"render": function (data) {
return getShortDate(data);
},
"defaultContent": "",
"targets": 2
},
{
"class": "date-time",
"data": "timeStart",
"render": function (data) {
return getTimeString(data);
},
"defaultContent": "",
"targets": 3
},
{
"class": 'number',
"data": "origNumber",
"defaultContent": "",
"orderable": true,
"targets": 4
},
{
"class": 'number',
"data": "destNumber",
"defaultContent": "",
"orderable": true,
"targets": 5
},
{
"class": 'cost',
"data": "totalAmount",
"render": function (data) {
return "$"+data.toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, '$1,');
},
"defaultContent": "",
"targets": 6
},
{
"class": 'duration',
"data": "callDuration",
"defaultContent": "00:00:00",
"orderable": false,
"targets": 7
}
],
"order": [[ 2, "desc" ]]
});
$('#backToSummary').click(function(e){
e.preventDefault();
$('form#call-history-options').submit();
});
});</script>
Add this to the css div z-index: value;

Push AJAX retrieved JSON into Datatables

I'm using the datatables plugin and it's working fine for me. However, I'm making multiple calls to populate multiple tables, when I know I could make one AJAX call and store the results in a variable and have each table function use that variable for its data, but I can't get it to work.
I'm using something like to to get the data I need.
var all_data;
$.ajax({
async : false,
url: 'all_data.php',
type: 'GET',
success: function(data) {
all_data = data;
console.log(all_data);
}
})
The idea is to pass all_data variable into my table function (I have several on this one page) without having to make multiple calls. Doing the following returns one column with the letter "a", which isn't right. The data that comes back is JSON coded. I've used the below code, but with the AJAX function as part of the table function:
$("#my_table").DataTable({
"data":all_data
,
"paging": true,
"sDom": '<"top">t<"bottom"><"clear">',
"pageLength": 50,
"order": [[ 4, "desc" ]],
"aoColumns": [
{ "bSortable": true, "width": "0%", "sClass": "lang_body_2", "sTitle": "","visible":false },
{ "bSortable": true, "searchable": false, "width": "10%", "sClass": "lang_body_2 table_names", "sTitle": "" },
{ "bSortable": true, "searchable": false,"width": "20%", "sClass": "lang_body_2", "sTitle": "Database","visible":false},
{ "bSortable": true, "searchable": false ,"width": "20%","sClass": "lang_body_2","sTitle": "National Average","visible":false },
{ "bSortable": true, "searchable": false ,"width": "50%","sClass": "lang_body_2 index_num table_index","sTitle": "" },
],
"columns": [
{ "searchable": true },
{ "searchable": false },
{ "searchable": false },
{ "searchable": false },
{ "searchable": false },
],
"search": {
"search": "gen"
},
"columns": [
{ "width": "20%" },
null,
null,
null,
{ "width": "80%" },
],
"initComplete": function(settings, json) {
colorIndex();}
});
});
What am I doing wrong here? I'm suspecting I have to prepare all_data somehow, but I'm not sure what that might be.
EDIT: If I console.log the data returned, this is what I get (cut off for brevity):
Object {draw: 0, recordsTotal: 484, recordsFiltered: 484, data: Array[484]}
data: Array[484]
[0 … 99]
0: Array[5]
0: "edu"1: "High School"2: "37.90"3: "49.70"4: "76"length: 5
Your code looks fine, the only thing you need to do is
Assign your datatable to a variable and then in your ajax resolve clear, add data and draw the table.
var all_data;
$.ajax({
async : false,
url: 'all_data.php',
type: 'GET',
success: function(data) {
all_data = data;
console.log(all_data);
table.clear().row.add(all_data).draw(); //clear, add data and draw
}
});
// Assign your datatable to a variable
var table = $("#my_table").DataTable({
"data":all_data
,
"paging": true,
"sDom": '<"top">t<"bottom"><"clear">',
"pageLength": 50,
"order": [[ 4, "desc" ]],
"aoColumns": [
{ "bSortable": true, "width": "0%", "sClass": "lang_body_2", "sTitle": "","visible":false },
{ "bSortable": true, "searchable": false, "width": "10%", "sClass": "lang_body_2 table_names", "sTitle": "" },
{ "bSortable": true, "searchable": false,"width": "20%", "sClass": "lang_body_2", "sTitle": "Database","visible":false},
{ "bSortable": true, "searchable": false ,"width": "20%","sClass": "lang_body_2","sTitle": "National Average","visible":false },
{ "bSortable": true, "searchable": false ,"width": "50%","sClass": "lang_body_2 index_num table_index","sTitle": "" },
],
"columns": [
{ "searchable": true },
{ "searchable": false },
{ "searchable": false },
{ "searchable": false },
{ "searchable": false },
],
"search": {
"search": "gen"
},
"columns": [
{ "width": "20%" },
null,
null,
null,
{ "width": "80%" },
],
"initComplete": function(settings, json) {
colorIndex();}
});
});

jquery Datatables add row. https://datatables.net

I am trying to ad a row to my java script data table (https://datatables.net)
ReportTable = $('#ReportsTable').dataTable({
//"data": Reportdata,
"bLengthChange": false,
"columns": [
{ "data": "name", "sTitle": "Name", "sWidth": "300px"},
{ "data": "type", "sTitle": "Report Type" },
{ "data": "timestamp", "sTitle": "Purchase Date" }
]
});
ReportTable.row.add("{name:'Test', type:'test', timestamp:'test'}").draw();
I have been following pages https://datatables.net/reference/api/rows.add() and http://www.datatables.net/examples/api/add_row.html with no luck.
The error i am getting reads as follows:
Uncaught TypeError: Cannot read property 'add' of undefined
ReportTable = $('#ReportsTable').dataTable(
must be
ReportTable = $('#ReportsTable').DataTable(
Why don't you try with:
ReportTable.row.add(['Test','test','test']).draw();
Because you added your columns name to your Datatable definition.
Swap out the DataTables include script with the following:
//cdn.datatables.net/1.10.3/js/jquery.dataTables.min.js
I'm guessing you are using an outdated version that does not include the API you are trying to use.
You would have to rewrite to the following:
$('#ReportsTable').dataTable({
//"data": Reportdata,
"bLengthChange": false,
"columns": [
{ "data": "name", "sTitle": "Name", "sWidth": "300px"},
{ "data": "type", "sTitle": "Report Type" },
{ "data": "timestamp", "sTitle": "Purchase Date" }
]
});
var ReportTable = $('#ReportsTable').dataTable();
ReportTable.row.add("{name:'Test', type:'test', timestamp:'test'}").draw();

Uncaught TypeError: Object [object Object] has no method 'fnFilterClear'

I am getting this error in the console :
"Uncaught TypeError: Object [object Object] has no method 'fnFilterClear'"
My code :
$(document).ready(function () {
var selectedColumn = $('#columnlist').find(":selected").text();
$('#csearchtext').bind("change paste keyup", function () {
var input = $('#csearchtext').val();
var dropdownindex = $("select[name='columnlist'] option:selected").index();
console.log(dropdownindex);
$('#table_id').dataTable().fnFilter(input, dropdownindex + 1, false, true, true, false);
});
$('#columnlist').on('change', function () {
$('#table_id').dataTable().fnFilterClear();
});
$('#dblist').on('change', function () {
var selected = $('#dblist').find(":selected").text();
tablefill(selected);
});
$('#search').click(function () {
var selected = $('#dblist').find(":selected").text();
tablefill(selected);
});
function tablefill(selected) {
$('.advsearchbar').show();
$('#stable').show();
$('#table_id').dataTable({
"sAjaxSource": '/php/connect/searchtablequery.php',
"bProcessing": true,
"sScrollY": "500px",
"bDeferRender": true,
"bDestroy": true,
"sAjaxDataProp": "",
"fnServerParams": function (aoData) {
aoData.push({ "name": "db", "value": selected });
},
"aoColumns": [
{ "mData": "calldate" },
{ "mData": "recordingfile" },
{ "mData": "uniqueid" },
{ "mData": "src" },
{ "mData": "did" },
{ "mData": "lastapp" },
{ "mData": "dst" },
{ "mData": "disposition" },
{ "mData": "duration" },
{ "mData": "userfield" },
{ "mData": "accountcode"}],
"iDisplayLength": 20,
"bJQueryUI": true,
"sPaginationType": "full_numbers",
"sDom": '<"H"Tfr>t<"F"ip>',
"oTableTools": {
"sSwfPath": "/DataTables/extras/TableTools/media/swf/copy_csv_xls_pdf.swf",
"aButtons": [
"copy", "csv", "xls", "pdf",
{
"sExtends": "collection",
"sButtonText": "Save",
"aButtons": ["csv", "xls", "pdf"]
}]
}
});
}
});
The javascript is firing just fine but the one spot that triggers the fnfilterclear has that error prompted.
Look at http://datatables.net/plug-ins/api#how_to How to use Datatable Plug-in API. You have to include the function listed on that page to use the function.
To make use of one of the plug-in API functions below, you simply need to include it in the Javascript available for your page, after you load the DataTables library, but before you initialise the DataTable. After that, you will be able to initialise the table, and call the function on the resulting object.

jQuery AutoComplete plugin - minLength is taking no effect

The autocomplete is working fine, but it's displaying the auto suggestion box with 1 character, and I would like to change it to display the auto suggestion box only when the input is >=3.
I've been trying to insert 'minLength' option but it is not taking any effetct.
I've tried to modify the sixth line to:
.autocomplete(conf.opts, minLength: 3 || {});
But had no success.
Here's my JS file:
var myEditor;
// AutoComplete FieldType
$.fn.dataTable.Editor.fieldTypes.autoComplete = $.extend(true, {}, $.fn.dataTable.Editor.models.fieldType, {
"create": function (conf) {
conf._input = $('<input type="text" id="' + conf.id + '">')
.autocomplete(conf.opts || {});
return conf._input[0];
},
"get": function (conf) {
return conf._input.val();
},
"set": function (conf, val) {
conf._input.val(val);
},
"enable": function (conf) {
conf._input.autocomplete('enable');
},
"disable": function (conf) {
conf._input.autocomplete('disable');
},
// Non-standard Editor method - custom to this plug-in
"node": function (conf) {
return conf._input;
}
});
$(document).ready(function () {
myEditor = new $.fn.dataTable.Editor({
"ajaxUrl": "./php/pTreinamentos.php",
"domTable": "#example",
"fields": [{
"label": "Tema",
"name": "tema",
"type": "autoComplete",
"opts": {
"source": ['banana']
}
}
]
});
// DataTable
var oTable = $('#example').dataTable({
"sDom": "<'row-fluid'<'span6'T><'span6'f>r>t<'row-fluid'<'span6'i><'span6'p>>",
"sAjaxSource": "./php/pTreinamentos.php",
"bFilter": true,
"bAutoWidth": false,
"iDisplayLength": 20,
"aoColumns": [{
"mData": "tema"
}
],
"oTableTools": {
"sSwfPath": "../../TableTools/media/swf/copy_csv_xls_pdf.swf",
"sRowSelect": "single",
"sPaginationType": "bootstrap",
"aButtons": [{
"sExtends": "editor_create",
"editor": myEditor
}, {
"sExtends": "editor_edit",
"editor": myEditor
}, {
"sExtends": "editor_remove",
"editor": myEditor
}
]
}
});
});
The solution was to add the option inside the field structure.
"fields": [{
"label": "Data",
"name": "data",
"type": "autoComplete",
"opts": {
"source": ['banana'],
"minLength": 3
}

Categories

Resources