I have two DataTables defined in $(document).ready() as follows:
oProdTable1 = $('#productstable1').dataTable( {...} );
oProdTable2 = $('#productstable2').dataTable( {...} );
Outside of $(document).ready(), I try to reload them. When I put a breakpoint in the following success function, I find that oProdTable1 is defined, but oProdTable2 is undefined:
function addProduct(productLine) {
$.ajax({
type: "POST",
url: 'ajax-add-product.php',
data: { productLine: productLine},
success: function(data) {
oProdTable1.fnReloadAjax();
oProdTable2.fnReloadAjax();
}
});
}
I can't find a difference between the definitions of these two tables. I also am wondering why oProdTable1 does not need to be declared with "var", yet is defined. Any ideas?
EDIT: I should note that oProdTable1 appears correctly, but oProdTable2 requires me to click to sort by a column for the rows to appear.
EDIT2: I have tried putting addProduct() inside $(document).ready(). oProdTable1 is still undefined and oProdTable2 is still undefined. I tried putting oProdTable2 before oProdTable1 and now oProdTable1 doesn't even load and both tables are undefined!
EDIT3: Every DataTable in the code after oProdTable2 does not load and is undefined. I compared the oProdTable1 and oProdTable2 code using the Notepad++ compare plugin and cannot find any major differences such as missing braces that I think could cause this.
EDIT4: Here is the code for oProdTable2, which seems to be problematic:
oProdTable2 = $('#productstable2').dataTable( {
"aaSorting": [[ 1, "asc" ]],
"aoColumnDefs":[
{"aTargets":[0],"bSearchable":false,"bVisible": false},
{"aTargets":[1],"sWidth":"60px"},
{"aTargets":[2],"sWidth":"200px"},
{"aTargets":[3],"sWidth":"300px"},
{"aTargets":[4],"sWidth":"60px"},
{"aTargets":[5],"sWidth":"60px"},
{"aTargets":[6],"sWidth":"60px"},
{"aTargets":[7],"sWidth":"60px"},
{"aTargets":[8],"sWidth":"60px"},
{"aTargets":[9],"sWidth":"60px"},
{"aTargets":[10],"sWidth":"60px"},
{"aTargets":[11],"sWidth":"60px"},
{ "sClass": "usa", "aTargets": [ 4, 5 ] },
{ "sClass": "can", "aTargets": [ 6, 7 ] },
{ "sClass": "lat", "aTargets": [ 8, 9 ] },
],
"iDisplayLength": 100, //sets item limit for table
"bJQueryUI": true,
"bProcessing": true,
"bServerSide": true,
"bSortCellsTop": true,
//"bStateSave": true,
"bSortClasses": false,
"sDom": 'T<"clear">C<"fg-toolbar ui-widget-header ui-corner-tl ui-corner-tr ui-helper-clearfix"lfr>t<"fg-toolbar ui-widget-header ui-corner-bl ui-corner-br ui-helper-clearfix"ip>',
"oTableTools": {
"sRowSelect": "single",
"sSwfPath": "/swf/copy_cvs_xls_pdf.swf",
"aButtons":
[
//"Add Product" button
{
"sExtends": "text",
"sButtonText": "Add Product",
"fnClick": function ( nButton, oConfig, oFlash ) {
addProduct("2");
}
},
{
"sExtends": "collection",
"sButtonText": "Export",
"aButtons": [ "copy","print","csv", "xls", "pdf" ]
}
]
},
'sAjaxSource': 'ajax-getproductstable.php',
"fnServerParams": function ( aoData ) {
aoData.push( { "name": "productLine", "value": "2" } );
},
"fnInitComplete": function() {
var oSettings = $('#productstable2').dataTable().fnSettings();
for ( var i=0 ; i<oSettings.aoPreSearchCols.length ; i++ ){
if(oSettings.aoPreSearchCols[i].sSearch.length>0){
$("thead input")[i-1].value = oSettings.aoPreSearchCols[i].sSearch;
$("thead input")[i-1].className = "activefilter"; }
}
},
"fnRowCallback": function( nRow, aData, iDisplayIndex, iDisplayIndexFull ) {
var id = aData[0];
$(this.fnGetTds(nRow)[1]).addClass("editable").addClass("ref");
$(this.fnGetTds(nRow)[2]).addClass("edit_area").addClass("name");
$(this.fnGetTds(nRow)[3]).addClass("edit_area").addClass("description");
$(this.fnGetTds(nRow)[4]).addClass("editable").addClass("price_rtl_usa");
$(this.fnGetTds(nRow)[5]).addClass("editable").addClass("price_dlr_usa");
$(this.fnGetTds(nRow)[6]).addClass("editable").addClass("price_rtl_can");
$(this.fnGetTds(nRow)[7]).addClass("editable").addClass("price_dlr_can");
$(this.fnGetTds(nRow)[8]).addClass("editable").addClass("price_rtl_lat");
$(this.fnGetTds(nRow)[9]).addClass("editable").addClass("price_dlr_lat");
$(this.fnGetTds(nRow)[10]).addClass("editable").addClass("ins_val_rtl_usa");
$(this.fnGetTds(nRow)[11]).addClass("editable").addClass("ins_val_dlr_usa");
$(this.fnGetTds(nRow)[12]).addClass("editable").addClass("ins_val_rtl_can");
$(this.fnGetTds(nRow)[13]).addClass("editable").addClass("ins_val_dlr_can");
$(this.fnGetTds(nRow)[14]).addClass("editable").addClass("net_l");
$(this.fnGetTds(nRow)[15]).addClass("editable").addClass("net_w");
$(this.fnGetTds(nRow)[16]).addClass("editable").addClass("net_h");
$(this.fnGetTds(nRow)[17]).addClass("editable").addClass("net_weight");
$(this.fnGetTds(nRow)[18]).addClass("editable").addClass("packed_l");
$(this.fnGetTds(nRow)[19]).addClass("editable").addClass("packed_w");
$(this.fnGetTds(nRow)[20]).addClass("editable").addClass("packed_h");
$(this.fnGetTds(nRow)[21]).addClass("editable").addClass("packed_weight");
$(this.fnGetTds(nRow)[22]).addClass("editable").addClass("customs_cost");
$(this.fnGetTds(nRow)[23]).addClass("editable").addClass("customs_desc");
$(this.fnGetTds(nRow)[24]).addClass("editable").addClass("customs_code");
$(this.fnGetTds(nRow)[25]).addClass("editable").addClass("customs_origin");
$(this.fnGetTds(nRow)[26]).addClass("edit_area").addClass("note");
$(nRow).attr("id", id);
return nRow;
},
"fnDrawCallback": function () {
// CODE FOR EDITABLE INLINES
$(".edit_area_w").editable('ajax-edit-product-inline.php', {
type : 'mce',
submit : 'OK',
indicator : "Saving...",
tooltip : 'Click to edit...',
width : '500px',
height : '100px',
"callback": function( sValue, y ) {
$(this).removeClass('empty_edit');
$("#productstable tr").removeClass("just_edited");
$(this).parent().addClass("just_edited");
var aPos = oProdTable2.fnGetPosition( this );
var update = oProdTable2.fnUpdate( sValue, aPos[0], aPos[2], true, true);
},
"submitdata": function ( value, settings ) {
return {
"row_id": this.parentNode.getAttribute('id'),
"column": oProdTable2.fnGetPosition( this )[2]
};
}
});
$('.editable').editable('ajax-edit-product-inline.php', {
event : "dblclick",
"callback": function( sValue, y ) {
$(this).removeClass('empty_edit');
$("#productstable tr").removeClass("just_edited");
$(this).parent().addClass("just_edited");
var aPos = oProdTable2.fnGetPosition( this );
var update = oProdTable2.fnUpdate( sValue, aPos[0], aPos[2], true, true);
},
"submitdata": function ( value, settings ) {
return {
"row_id": this.parentNode.getAttribute('id'),
"column": oProdTable2.fnGetPosition( this )[2]
};
},
"height": "14px"
} );
$('.edit_area').editable('ajax-edit-product-inline.php', {
event : "dblclick",
type : "textarea",
cancel : 'Cancel',
submit : 'OK',
indicator : '<img src="img/indicator.gif">',
"callback": function( sValue, y ) {
$(this).removeClass('empty_edit');
$("#productstable tr").removeClass("just_edited");
$(this).parent().addClass("just_edited");
var aPos = oProdTable2.fnGetPosition( this );
oProdTable2.fnUpdate( sValue, aPos[0], aPos[2]);
},
"submitdata": function ( value, settings ) {
return {
"row_id": this.parentNode.getAttribute('id'),
"column": oProdTable2.fnGetPosition( this )[2]
};
},
} );
$('.edit_select').editable('ajax-edit-product-inline.php', {
event : "dblclick",
loaddata: function ( value, settings ) {
return {
"pid": $(this).parent().attr("id")
};
},
loadurl : 'ajax-part-selects.php',
loadtype: "GET",
type : 'select',
submit : 'OK',
"callback": function( sValue, y ) {
$(this).removeClass('empty_edit');
$("#productstable tr").removeClass("just_edited");
$(this).parent().addClass("just_edited");
var aPos = oProdTable2.fnGetPosition( this );
oProdTable2.fnUpdate( sValue, aPos[0], aPos[2]);
},
"submitdata": function ( value, settings ) {
return {
"row_id": this.parentNode.getAttribute('id'),
"column": oProdTable2.fnGetPosition( this )[2]
};
},
});
}
} );
$("#productstable2 .floating_filters input").keyup( function () {
// Filter on the column (the index) of this element
oProdTable2.fnFilter( this.value, $(".floating_filters input").index(this)+1 );
$(this).addClass("activefilter");
} );
$("#productstable2 .floating_filters input").each( function (i) {
asInitVals[i] = this.value;
} );
$("#productstable2 .floating_filters input").focus( function () {
if ( $(this).hasClass("search_init"))
{
this.className = "";
this.value = "";
}
} );
$("#productstable2 .floating_filters input").blur( function (i) {
if ( this.value == "" )
{
$(this).removeClass("activefilter");
$(this).addClass("search_init");
this.value = asInitVals[$(".floating_filters input").index(this)];
}
} );
I finally found the solution! The problem wasn't even with the javascript code, it was with the html. The table with the id "productstable2" had one less "td" than "th". I just needed to add an additional <td></td> to the list of "td"s.
Related
I'm working in CodeIgniter and i have a DataTable, i want to filter the data from the DT after the ajax has been called. I'm trying to do that by filtering the table, but it's not working.
Here's the JS Code.
$(function () {
var tableRep= $("#tblreport").dataTable({
responsive: true, filter:true, order: [[ 1, "desc" ]],
processing: true, serverSide: true,
ajax: { "url": baseurl+"reports/Report/dataTable", "type": "POST" },
columns:
[
{data:"idReport",},
{data:"date"},
{data:"customer"},
{data:"status",visible:false},
{data:null,searchable:false,orderable: false,width:"120px", render: function (row)
{ if (row.status == "wait") {return '<a class="glyphicon glyphicon-search" data-toggle="modal" data-target="#report">Asign</a>'; }
else if (row.status == "process") {return '<a data-toggle="modal" data-target="#report">Edit</a>';} else return '';} }
],
columnDefs:
[
{ responsivePriority: 1, targets: 1 },
{ responsivePriority: 2, targets: -1 },
{ responsivePriority: 3, targets: 2 }
], fnCreatedRow: function( nRow, aData, iDataIndex ) {
if ( aData["status"] == "ready" ) { $('td', nRow).css('background-color', '#BEF781'); }
else if ( aData["status"] == "wait" ) { $('td', nRow).css('background-color', '#F2F5A9'); }
else { $('td', nRow).css('background-color', '#FFFFFF'); }
}})
});
var filteredData = tableRep.column(4).data().filter( function ( value, index ) {return value!="cancel" ? true : false;} );
Did you try this option?
var tableRep= $("#tblreport").dataTable({
//your config
})
.on('draw.dt', function () {
//Add here yours filters
});
Hi have the java script for datatables as below, How can define it so that the search is done only for start values, eg : [ hello, hello_all, all_hello] is there and my search key word is "hel" i should get filter of [hello,hello_all].
$('#example').DataTable( {
data: new_data,
dom: '<"top"fB>rt<"bottom"ipl>',
buttons:['csv'],
search :{"bSmart": false,
"regex":true},
columns: [
{ title: "Action" },
{ title: "Input" },
{ title: "State" },
{ title: "Completed" },
{ title: "Project" },
],
"order": [[ 3, "desc" ]]
});
See the documentation:
https://datatables.net/examples/api/regex.html
The filterColumn function is what you looking for I think.
I hope that helps.
Gruesse
function filterGlobal () {
$('#example').DataTable().search(
$('#global_filter').val(),
$('#global_regex').prop('checked'),
$('#global_smart').prop('checked')
).draw();
}
function filterColumn ( i ) {
$('#example').DataTable().column( i ).search(
$('#col'+i+'_filter').val(),
$('#col'+i+'_regex').prop('checked'),
$('#col'+i+'_smart').prop('checked')
).draw();
}
$(document).ready(function() {
$('#example').DataTable();
$('input.global_filter').on( 'keyup click', function () {
filterGlobal();
} );
$('input.column_filter').on( 'keyup click', function () {
filterColumn( $(this).parents('tr').attr('data-column') );
} );
} );
I have a separate search field for one of the columns and here's my solution for begins-with search:
vm.searchForLocation = function() {
vm.dtInstance.DataTable.column(2)
.search("^"+vm.locationCode, true, false )
.draw();
}
I'm using datatables with custom buttons. I'm looking in the examples, also googled a bit but I didn't find a working solution.
The problem is that, when I deselect the row the button is still enabled. What is the proper way to enable/disable the buttons when a row is selected/deselected?
var table = $('#example').DataTable( {
serverSide: true,
dom: 'Bfrtip',
ajax: '/get?op=2',
columns: [
{ data: 'id' },
// more columns
],
buttons: [
{
text: 'New',
action: function ( e, dt, node, config ) {
window.location.href = '/property?option=new'
}
},
{
text: 'Modify',
action: function ( e, dt, node, config ) {
window.location.href = '/property?option=modify&id=' + data.id
},
enabled: false
},
{
text: 'Delete',
action: function ( e, dt, node, config ) {
},
enabled: false
}
],
select: true
} );
table.on( 'select', function () {
var selectedRows = table.rows( { selected: true } ).count();
table.button( 1 ).enable( selectedRows === 1 );
table.button( 2 ).enable( selectedRows === 1 );
table.button( 3 ).enable( selectedRows === 1 );
//table.button( 1 ).enable( selectedRows > 0 );
} );
Also how can I get the id value for the selected row?
action: function ( e, dt, node, config ) {
window.location.href = '/property?option=modify&id=' + data.id
},
You need to add an event handler for the deselect. see https://datatables.net/reference/event/deselect
It should be something like below...
table.on( 'deselect', function () {
table.button( 1 ).disable();
table.button( 2 ).disable();
table.button( 3 ).disable();
} );
As for getting a row id an example can be found here
I think you are a bit confused over the .id() function you are using. It does not return value of you data field called id. It returns the tr attribute of id. If you do not set it, it will return undefined.
if you return DT_RowId as part of your dataset, it will be added automatically. {id:5, DT_RowId:"5"}. Or, client side, use the JQuery map function to add the field before you use it. Because using a straight integer as an id, it could get you in trouble if it gets duplicated in another table or element so I ususally do something like this...
var mydata = [{"name": "Tiger Nixon",
"position": "System Architect",
"salary": "$320,800",
"start_date": "2011/04/25",
"office": "Edinburgh",
"extn": "5421"
}];
Using the extn id, I map to the dt_rowid...
$.map(mydata, function (item, key) {
item["DT_RowId"] = item["extn"]});
then use that data in my table...
$(document).ready(function() {
$('#example').DataTable( {
data:mydata,
"columns": [
{ "data": "name" },
{ "data": "position" },
{ "data": "office" },
{ "data": "extn" },
{ "data": "start_date" },
{ "data": "salary" }
]
} );
} );
I want to do some operations after clicking a particular row. I followed the API and this is what I ended up with but the click event is not working.
$(document).ready(function() {
table = $('#employees').dataTable( {
"bJQueryUI": true,
"bProcessing": true,
"bServerSide": true,
"sAjaxSource": "show_employee_processor.php",
"aoColumns": [
{ "sTitle": "Empoyee ID" },
{ "sTitle": "Last Name" },
{ "sTitle": "First Name" },
{ "sTitle": "BBan Number" },
]
} );
table.$('tr').click(function() {
var data = table.fnGetData( this );
alert(data);
});
} );
The datatable is getting drawn but the click event is not working. What am I missing?
try delegated event:
table.on('click','tr',function() {
var data = table.fnGetData( this );
alert(data);
});
or:
$('#employees').on('click','tr',function() {
var data = table.fnGetData( this );
alert(data);
});
$("#employees tr").click( function( e ) {
if ( $(this).hasClass('row_selected')==false ) {
table .$('tr.row_selected').removeClass('row_selected');
$(this).addClass('row_selected');
var data = table.fnGetData( this );
alert(data);
}
else{
$(this).removeClass('row_selected');
}
});
CSS>
#employees tr.row_selected{
background-color:#B5CCD2;
opacity:0.95;
font-weight:bold;
}
I'm having a jQuery DataTable that is generated from a JSON file. All works fine, but as it comes to conditional formatting, I get stuck. The following script gives all cells in column 2 a 'positive' class (even negative integers). What's wrong with my if-statement?
"fnRowCallback": function( nRow, aData, iDisplayIndex, iDisplayIndexFull ) {
if ( parseFloat(aData[1]) <= 0 ) {
jQuery('td:eq(1)', nRow).addClass('negative');
} else {
jQuery('td:eq(1)', nRow).addClass('positive');
}
return nRow;
}
thanks in advance!
edit: a part of the JSON file (the number I'm referring to is "punten":
[
{
"spel_id": "2012-09-24 15:43:56",
"locatie": "white room",
"speler": "Arne",
"punten": "17"
},
{
"spel_id": "2012-09-24 15:43:56",
"locatie": "white room",
"speler": "Bjorg",
"punten": "26"
}
]
and my js to generate the table (using DataTables):
$(document).ready( function() {
var oTable = $('#example').dataTable( {
"sAjaxSource": "json_gespeeldekaartings.php",
"aoColumns": [
{ "mData": "kaarting"},
{ "mData": "speler" },
{ "mData": "punten"}
],
"sAjaxDataProp": "",
"sPaginationType": "full_numbers",
"aaSorting": [],
"fnRowCallback": function( nRow, aData, iDisplayIndex, iDisplayIndexFull ) {
if ( parseFloat(aData[1]) <= 0 ) {
jQuery('td:eq(1)', nRow).addClass('negative');
} else {
jQuery('td:eq(1)', nRow).addClass('positive');
}
return nRow;
}
} )
} );
inster of
if ( parseFloat(aData[1]) <= 0 ) {
use
if ( parseFloat(aData.punten <= 0 )
EDIT
try this :
remove fnRowCallback and use mRender for in this example :
...
"aoColumns": [
{ "mData": "kaarting"},
{ "mData": "speler" },
{ "mData": "punten",
"sType": "numeric",
"mRender": function ( data, type, full ) {
if(data > 0) return "<div class='positive'>" + data + "</div>"; // example
return "<div class='negative'>" + data + "</div>"; // example
}
}
],
...