Datatables is not initializing columnFilter plugin - javascript

I already have a table
<table id="currencies-table" class="table table-striped table-bordered table-hover form-data-table">
<thead>
<tr>
<th style="width: 10px;"><input type="checkbox" class="group-checkable" data-set=".form-data-table .checkboxes" /></th>
<th><spring:message code="label.name_pl"/></th>
<th><spring:message code="label.name_en"/></th>
<th><spring:message code="label.name_de"/></th>
<th><spring:message code="label.code"/></th>
<th><spring:message code="label.symbol" /></th>
<th class="num-html-sort"><spring:message code="label.order" /></th>
<th></th>
</tr>
</thead>
<tbody>
<c:forEach var="currency" items="${model.currencies}">
<tr class="odd gradeX">
<td><sf:checkbox path="ids" class="checkboxes" value="${currency.id}"/></td>
<td>${currency.name.pl}</td>
<td>${currency.name.en}</td>
<td>${currency.name.de}</td>
<td>${currency.code}</td>
<td>${currency.symbol}</td>
<td class="center">
<span class="move-arrow move-arrow-down" style="cursor:pointer"><i class="icon-arrow-down"></i></span>
<span class="priority-order badge badge-inverse">${currency.priority}</span>
<span class="move-arrow move-arrow-up" style="cursor:pointer"><i class="icon-arrow-up"></i></span>
</td>
<td><spring:message code="label.details"/></td>
</tr>
</c:forEach>
</tbody>
<tfoot>
<tr>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
</tr>
</tfoot>
</table>
This is the script that initializes this table.
var defaultSettings = function() {
return {
"bStateSave": true,
"bFilter": true,
"aLengthMenu": [
[5, 15, 20, -1],
[5, 15, 20, Labels.getLabel('label.all')] // change per page values here
],
"iDisplayLength": 15,
"sDom": "<'row-fluid'<'span6'l><'span6'f>r>t<'row-fluid'<'span6'i><'span6'p>>",
"sPaginationType": "bootstrap",
"oLanguage": {
"sUrl": CommonsValues.datatable_lang_path()
},
"aoColumnDefs": [{
'bSortable': false,
'bSearchable': false,
'aTargets': [0, 'no-sort']
},
{
'bSortable': true,
'aTargets': ['date-sort'],
'sType': "date-pl"
},
{
'bSortable': true,
'aTargets': ['datetime-sort'],
'sType': "date-euro"
},
{
'sWidth': "100px",
'aTargets': ['size100']
},
{
'bSortable': true,
'aTargets': ['numeric-sort'],
'sType': "numeric"
},
{
'bSortable': true,
'aTargets': ['num-html-sort'],
'sType': 'num-html'
},
{
'bSortable': true,
'bSearchable': true,
'aTargets': ['rfq-sort'],
'sType': "rfq",
'mData': function(source, type, val) {
if (type === 'set') {
source.value = val;
source.value_display = val;
source.value_filter = val === "" ? "" : $.fn.dataTableExt.ofnSearch['rfq'](val);
return;
}
else if (type === 'display') {
return source.value_display;
}
else if (type === 'filter') {
return source.value_filter;
}
// 'sort', 'type' and undefined all just use the integer
return source.value;
}
},
{
'bSortable': true,
'aTargets': ['offer-sort'],
'sType': 'offer'
},
{
'bSortable': true,
'aTargets': ['price-sort'],
'sType': 'price'
}
],
"fnDrawCallback": function(oSettings) {
$('.group-checkable', oSettings.nTableWrapper).on('change', function() {
var checked = $(this).is(":checked");
$(oSettings.oInstance.fnGetNodes()).each(function() {
if (checked) {
$(this).find('.checkboxes').attr("checked", true);
} else {
$(this).find('.checkboxes').attr("checked", false);
}
$.uniform.update($(this).find('.checkboxes'));
});
}
);
}
};
};
var settings = new defaultSettings();
if ($(this).hasClass('expand-table')) {
settings.sScrollX = "125%";
}
var dataTable = $(this).dataTable(settings).columnFilter({
"sPlaceHolder": "head:after",
"aoColumns": [
null,
null,
{type: "checkbox"},
{type: "checkbox"},
{type: "checkbox"},
null,
null,
null
]
});
After initialization the table doesn't have the input for filtering columns even though other features works (sorting, main filtering, paging).
The table elements (thead,tbody,tfoot) are swapped in the resulting html code.

From what I can see from the provided example code I would say that you forgot to configure the values for the checkbox filters.
The followering should work:
var dataTable = $(this).dataTable(settings).columnFilter({
"sPlaceHolder": "head:after",
"aoColumns": [
null,
null,
{type: "checkbox", values: [ 'value used for filtering', 'displayed label text for checkbox']},
{type: "checkbox", values: ['bemol', 'user']},
{type: "checkbox", values: ['pl','Polish']},
null,
null,
null
]
});
Also try checking this example out:
Checkbox example

Related

Change the page length of each page in datatable

I have the below datatable on my jsp page for which I want to change the page length on each page.I have tried 3 approaches but the page length is not getting changed. I have used the "lengthChange" option as "true". But it is also not working
$(document).ready(
function() {
document.getElementById("invoiceResult").style.display="block";
dTable = $('#result').DataTable(
{
paging : true,
"lengthChange": true,
fixedHeader : true,
"scrollY" : 400,
"scrollX" : true,
"bJQueryUI" : true,
fixedColumns : true,
"pageLength" : 25,
"order" : [ [ 4, "desc" ] ],
"columnDefs" : [ {
"width" : "100px",
"targets" : 0
} ],
drawCallback: function(){
$('#result').margetable({
type: 2,
colindex: [0,1],
});
},
rowsGroup: [0,1]
});
//This method is called whenever the page is redrawn
$('#result').on( 'draw.dt', function () {
var info = table.page.info();
var currentPage = info.page + 1;
if(currentPage==2){
//approach 1:
$('#result').DataTable.page.len(80).draw();
//approach 2:
$('#result').DataTable.getPager().config.size = 80;
$('#result').DataTable.refresh();
//approach 3:
$('#result').DataTable({ pageLength: 80 });
}
});
I'm not sure about the issue you're having, but in my example (with your options) I went for the lengthChange approach, and it's working fine:
//var dataUrl = "https://my-json-server.typicode.com/SagnalracSO/repoJD/employees?_limit=7";
var dataUrl = "https://my-json-server.typicode.com/SagnalracSO/repoJD/employees";
var table = $('#example').DataTable({
ajax: {
url: dataUrl,
dataSrc: ''
},
lengthChange: true,
pageLength: 25,
scrollY : 400,
scrollX : true,
bJQueryUI : true,
fixedColumns : true,
order : [ [ 4, "desc" ] ],
columnDefs : [ {
width : "100px",
targets : 0
}],
drawCallback: function() {
$('#example').margetable({
type: 2,
colindex: [0,1]
});
},
rowsGroup: [0, 1],
columns: [
{ data: 'id' },
{ data: 'firstName' },
{ data: 'lastName' },
{ data: 'position' },
{ data: 'office' },
{ data: 'age' },
{ data: 'startDate' }
]
});
<link href="https://cdn.datatables.net/1.10.21/css/jquery.dataTables.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script>
<script src="https://www.jqueryscript.net/demo/Merge-Cells-HTML-Table/jquery.table.marge.js"></script>
<table id="example" class="display" style="width:100%">
<thead>
<tr>
<th>Id</th>
<th>First Name</th>
<th>Last Name</th>
<th>Position</th>
<th>Office</th>
<th>Age</th>
<th>Start Date</th>
</tr>
</thead>
</table>
<br>

How to add buttons to each row of a datatable?

$(document).ready(function() {
var table = $('#example').DataTable({
"columns": [
{ "data": "id" },
{ "data": "itemID" },
{ "data": "imagePath" },
{
"className": 'details-control',
"orderable": false,
"data": null,
"defaultContent": ''
},
{ "data": "icon" },
{ "data": "reporter" },
{ "data": "title" },
{ "data": "dateUploaded" },
{ "data": "dateReported" },
{ "data": "reportedReason" },
{ "data": "description" },
{ "data": "problem" },
{ "data": "numReports" },
{ "data": "deleteImage" }
],
"columnDefs":
[
{
"targets": 0,
"visible": false
},
{
"targets": 1,
"visible": false
},
{
"targets": 2,
"visible": false
},
{
"data": null,
"defaultContent": "<button>Delete</button>",
"targets": -1
}
]
});
]);
Note: The final td in the tbody has been left blank.
<table id="example" class="sortable table table-bordered table-striped table-hover">
<thead>
<?php
foreach($report_flag_info as $flag_info){
?>
<tr>
<th>ID</th>
<th>ItemID</th>
<th>Image Path</th>
<th>Image</th>
<th>Reporter</th>
<th>Title</th>
<th>Image</th>
<th>Uploaded</th>
<th>Reported</th>
<th>Reason</th>
<th>Description</th>
<th>Problem</th>
<th>No. Times Reported</th>
<th>Delete Image</th> // I want the button to be in this column
</tr>
</thead>
<tbody>
<?php
foreach($report as $flag_info){
?>
<tr>
<td></td>...
</tr>
<?php } ?>
</tbody>
</table>
The table in the html is populated by using a foreach loop to load the data from the server to the table. I tried the suggestion in the following links to
solve the issue.
https://datatables.net/reference/option/columns.defaultContent
How do I add button on each row in datatable?
https://datatables.net/examples/ajax/null_data_source.html
How add more then one button in each row in JQuery datatables and how to apply event on them
The fact that conumDefs Option was applied before columns.data, meant that columns.data Option config { "data": "deleteImage" }
is overwriting the columnDefs option that is building the button. Changing { "data": "deleteImage" } to { "data": null } prevented
the button being overwritten and hence, solved the problem.

dataTable not display ajax data

I need your helps guys. to correct what's wrong with the code.
I want to copy the row table on table1 into table2, but the data does not show up when I use ajax json. have to insert manually into html.
JSFiddle
I want to copy the row table on datatable, but the data does not show up when I use ajax json.
Code Snippet Demonstration
// Code goes here
$(document).ready(function() {
var stockTable = $('#table1').dataTable({
"ajax": "https://api.myjson.com/bins/zvujb",
"columns": [{
"data": "id"
}, {
"data": "name"
}, {
"data": "subtype"
}, {
"data": "approximate_count"
}, {
"data": "time_created"
}],
"columnDefs": [{
"targets": 0,
"checkboxes": {
"selectRow": true
},
"searchable": false,
"orderable": false,
"className": 'dt-body-center',
"render": function(data, type, full, meta) {
return '<input type="checkbox" name="id[]" value="' + $('<div/>').text(data).html() + '">';
}
}],
"select": {
"style": "multi"
},
"order": [
[4, "desc"]
],
"scrollY": "400px",
"scrollCollapse": true,
}); // first table
var catalogTable = $('#table2').dataTable(); // Second table
stockTable.on('click', 'tbody tr' ,function() {
$(this).toggleClass('selected');
});
catalogTable.on('click', 'tbody tr' ,function() {
$(this).toggleClass('selected');
});
$('#LeftMove').on('click',function () {
moveRows(catalogTable, stockTable);
});
$('#RightMove').on('click',function () {
moveRows(stockTable, catalogTable);
});
});
function moveRows(fromTable, toTable){
var $row= fromTable.find(".selected");
$.each($row, function(k, v){
if(this !== null){
addRow = fromTable.fnGetData(this);
toTable.fnAddData(addRow);
fromTable.fnDeleteRow(this);
}
});
}
/* Styles go here */
#table2_wrapper{
margin-top:50px;
margin-left:50px;
}
#table1_wrapper{
margin-left:50px;
}
table.dataTable tbody tr.selected {
background-color: #b0bed9;
}
table.dataTable.display tbody tr.odd.selected > .sorting_1, table.dataTable.order-column.stripe tbody tr.odd.selected > .sorting_1 {
background-color: #a6b3cd;
}
table.dataTable.display tbody tr:hover.selected > .sorting_1, table.dataTable.display tbody tr.odd:hover.selected > .sorting_1, table.dataTable.display tbody tr.even:hover.selected > .sorting_1, table.dataTable.order-column.hover tbody tr:hover.selected > .sorting_1, table.dataTable.order-column.hover tbody tr.odd:hover.selected > .sorting_1, table.dataTable.order-column.hover tbody tr.even:hover.selected > .sorting_1 {
background-color: #a1aec7;
}
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.1.min.js"></script>
<script src="https://ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.0/jquery.dataTables.min.js"></script>
<link href="https://ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.0/css/jquery.dataTables.css" rel="stylesheet"/>
<link href="https://ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.0/css/jquery.dataTables_themeroller.css" rel="stylesheet"/>
<body>
<div class="one" style="padding-bottom:50px">
<table id="table1" class="table table-bordered table-hover">
<thead>
<tr>
<th></th>
<th>Audience Name</th>
<th>Type</th>
<th>Size</th>
<th>Date Created</th>
</tr>
</thead>
</table>
</div>
<center>
<button id="RightMove" style="float:left;">right »</button>
<button id="LeftMove" style="float:left;">« left</button>
</center>
<br>
<br>
<div class="two">
<table id="table2" class="table table-bordered table-hover">
<thead>
<tr>
<th></th>
<th>Audience Name</th>
<th>Type</th>
<th>Size</th>
<th>Date Created</th>
</tr>
</thead>
</table>
</div>
</body>
Edit your ajax call as follows
ajax: {
"url": "https://api.myjson.com/bins/zvujb",
"type": "GET",
"error": function (e) {
},
"dataSrc": function (d) {
return d
}
},
[Problem Solved] https://jsfiddle.net/4fukuma/o6ysgzps/2/
Change jquery file, using jquery-1.12.4.js
and edit table2 js code == table1
$(document).ready(function() {
var stockTable = $('#table1').dataTable({
"ajax": "https://api.myjson.com/bins/zvujb",
"columns": [{
"data": "id"
}, {
"data": "name"
}, {
"data": "subtype"
}, {
"data": "approximate_count"
}, {
"data": "time_created"
}],
"columnDefs": [{
"targets": 0,
"checkboxes": {
"selectRow": true
},
"searchable": false,
"orderable": false,
"className": 'dt-body-center',
"render": function(data, type, full, meta) {
return '<input type="checkbox" name="id[]" value="' + $('<div/>').text(data).html() + '">';
}
}],
"select": {
"style": "multi"
},
"order": [
[4, "desc"]
],
"scrollY": "400px",
"scrollCollapse": true,
}); // first table
var catalogTable = $('#table2').dataTable({
"columns": [{
"data": "id"
}, {
"data": "name"
}, {
"data": "subtype"
}, {
"data": "approximate_count"
}, {
"data": "time_created"
}],
"columnDefs": [{
"targets": 0,
"checkboxes": {
"selectRow": true
},
"searchable": false,
"orderable": false,
"className": 'dt-body-center',
"render": function(data, type, full, meta) {
return '<input type="checkbox" name="id[]" value="' + $('<div/>').text(data).html() + '">';
}
}],
"select": {
"style": "multi"
},
"order": [
[4, "desc"]
],
"scrollY": "400px",
"scrollCollapse": true,
}); // Second table
stockTable.on('click', 'tbody tr' ,function() {
$(this).toggleClass('selected');
});
catalogTable.on('click', 'tbody tr' ,function() {
$(this).toggleClass('selected');
});
$('#LeftMove').on('click',function () {
moveRows(catalogTable, stockTable);
});
$('#RightMove').on('click',function () {
moveRows(stockTable, catalogTable);
});
});
function moveRows(fromTable, toTable){
var $row= fromTable.find(".selected");
$.each($row, function(k, v){
if(this !== null){
addRow = fromTable.fnGetData(this);
toTable.fnAddData(addRow);
fromTable.fnDeleteRow(this);
}
});
}

Datatable aoColumnDefs is not working as expected

I am facing an issue with Datatable .
<table id="example1" class="table table-bordered table-striped">
<thead>
<tr>
<c:forEach items="${Details.columns}" var="column">
<th>${column.columnTitle}</th>
</c:forEach>
</tr>
</thead>
<tfoot>
<tr>
<c:forEach items="${Details.columns}" var="column">
<th></th>
</c:forEach>
</tr>
</tfoot>
<tbody>
<c:forEach items="${Details.callList}" var="call">
<tr>
<c:forEach items="${call.attributes}" var="attribute">
<td>${attribute.value}</td>
</c:forEach>
</tr>
</c:forEach>
</tbody>
</table>
$("#example1").dataTable({
'sDom': '"top"i',
//"aoColumnDefs": [{ "bSearchable": true, "aTargets": [1] }],
"bPaginate" : true,
"bLengthChange" : false,
//"bFilter" : true,
"bSearchable": true,
"bSort" : true,
"bInfo" : true,
"bAutoWidth" : false,
"iDisplayLength": 5
//}).columnFilter({"aoColumns": [{ "type": "text" }, { "type": "text" }, null]});
}).columnFilter({"aoColumnDefs": [{ "bSearchable": true, "aTargets": [2] }]});
From the above snippet.. i am trying to remove the filter/search for last column alone.
Here "aoColumns" works as expected - It removes the filter in last column as i coded,
However i am unable to use "aoColumns" . Since the columns in this table is dynamic/configurable, so it is tough for me to change the code everytime.
It would be really grateful if anyone can help me here..
Thanks,
This is how I use Datatables and it works like a charm. I don't do sorting at client-side, I do it at server-side using AJAX, but the configuration for the table should be the same except for "bServerSide=true". Let me know if this solves your problem:
var oTable = $('#tblMainTable').dataTable({
"searching": false,
"bStateSave": true,
"fnStateSave": function (oSettings, oData) {
localStorage.setItem('jobTitlesDataTables', JSON.stringify(oData));
},
"fnStateLoad": function (oSettings) {
return JSON.parse(localStorage.getItem('jobTitlesDataTables'));
},
"pagingType": "full_numbers",
"bLengthChange": false,
"bAutoWidth": false,
"iDisplayLength": 2000,
"bServerSide": true, // server side
"sAjaxSource": BASE_URL + "Job/GetJobTitleMappingDTOs", // AJAX URL
"bProcessing": true,
"fnServerData": function (sSource, aoData, fnCallback, oSettings) {
// send data from client-side to server-side
aoData.push({ "name": "IsMapped", "value": $("#bdgIsMapped").data("selected") });
aoData.push({ "name": "IsSearchableOption", "value": $("#bdgIsSearchable").data("selected") });
aoData.push({ "name": "timestamp", "value": new Date().getTime() }); // Added to avoid caching in some IE versions.
oSettings.jqXHR = $.ajax({
"dataType": 'json',
"type": "GET",
"url": sSource,
"data": aoData,
"cache": false,
"success": function (json) {
// shows records count next to the top title
if (json.iTotalRecords > 0) {
$("#resultsDescription").text(" - " + json.iTotalRecords + " rows.");
}
else {
$("#resultsDescription").text(" - No results.");
}
// shows paginator when necessary
if (json.iTotalRecords > json.iDisplayLength) {
$(".dataTables_paginate").show();
}
else {
$(".dataTables_paginate").hide();
}
$("#isFirstSearch").val("false");
fnCallback(json);
}
});
},
"aoColumnDefs": [
{
sType: "numeric",
mData: "RowNumber",
aTargets: [0],
mRender: function (data, type, full) {
// this is for custom rendering a column just in case you need it
// 'full' is the row's data object, and 'data' is this column's data
return '<span class="RowNumber">' + full.RowNumber + '</span>';
}
},
{
sType: "numeric",
mData: "JobTitleId",
aTargets: [1],
mRender: function (data, type, full) {
// 'full' is the row's data object, and 'data' is this column's data
return '<span class="EditableJobTitleId" data-job-title-id="' + full.JobTitleId + '">' + full.JobTitleId + '</span>';
}
},
{
sType: "string",
mData: "JobTitle",
aTargets: [2]
}
],
"order": [[1, "asc"]]
});

jQuery datatables TypeError: b is null

I am facing with a error fired by Firebug when using a jquery datatables plugin
The table is like this:
<table id="dt_cursuri" class="table table-striped table-bordered dTableR">
<thead>
<tr>
<th data-class="expand">Curs</th>
<th data-hide="phone,tablet" data-name="Assign">Domeniu</th>
<th>Tip</th>
<th>Data modif</th>
<th class="centered-cell">Actiuni</th>
</tr>
</thead>
<tbody>
<tr>
<td class="dataTables_empty" colspan="6">Fetching data from server</td>
</tr>
</tbody>
</table>
The datatables initialization:
var oTable;
var responsiveHelper = undefined;
var breakpointDefinition = {
tablet: 1024,
phone : 480
};
var oTable = $('#dt_cursuri');
oTable = $('#dt_cursuri').dataTable( {
"bProcessing": true,
"bServerSide": true,
"sPaginationType": "bootstrap",
"sDom": "<'row'<'col-md-6'l><'col-md-6'f>r>t<'row'<'col-md-6'i><'col-md-6'p>>",
"sAjaxSource": "view/cursuri/server_side.php",
autoWidth : false,
"fnPreDrawCallback": function () {
// Initialize the responsive datatables helper once.
if (!responsiveHelper) {
responsiveHelper = new ResponsiveDatatablesHelper(oTable, breakpointDefinition);
}
},
"fnDrawCallback" : function (oSettings) {
responsiveHelper.respond();
},
"fnRowCallback": function( nRow, aData ) {
responsiveHelper.createExpandIcon(nRow);
},
"aoColumns": [
//{ "sClass": "center", "bSortable": false, sWidth: '2%', "bVisible": false },
{ sWidth: '35%' },
{ sWidth: '25%' },
{ sWidth: '20%' },
{ sWidth: '10%' },
{ "sClass": "center", sWidth: '10%', "bSortable": false }
],
"aaSorting": [[2, 'asc']]
} );
The server side json file is working corectly. The same code is used in other tables that work perfect, but this one is not
Could someone help me?
The error is fired for this line from jquery.datatables.js:
!a.sLoadingRecords && (c && 'Loading...' === b.sLoadingRecords) && D(a, a, 'sZeroRecords', 'sLoadingRecords');
I will answer this question on my own thanks to developers of jQuery Datatables.
The problem was in the server side processing. When using diacritics the datatable is messing with the data so you have to actually control the diacritics with utf8_encode() php function

Categories

Resources