Hiding column in jQuery dataTables - datatables

I have problem hiding jQuery datatable column. I want that column to retrieve data but I don't want it to be shown on the display page. I want to hide my column no 8 so from CSS I tried hiding it and it gives me collapsable div.
Below is my code for data table and class for hiding is "hideCol".
var userTable = $('#user').dataTable( {
"processing": true,
"serverSide": true,
"ajax":"admin/getData.php",
"responsive" : true,
"lengthMenu": [10, 25],
"paginationType" : "input",
columns: [
{ data:'param0'},
{ data: 'param1' },
{ data: 'param2' },
{ data: 'param3' },
{ data: 'param4' },
{ data: 'param5' },
{ data: 'param6' },
{ data: 'param7'},
],
fnRowCallback:function(nRow,aData, iDisplayIndex, iDisplayIndexFull){
var seenReportedVal =Number($('td:eq(7)', nRow).text());
$('td:eq(7)', nRow).addClass('hideCol');
if(seenReportedVal==0)
{
$(nRow).addClass('bold');
}
},
"columnDefs": [
{ "visible": false, "targets": 7 }
],
});

try using this code
var userTable = $('#user').dataTable( {
"processing": true,
"serverSide": true,
"ajax":"admin/getData.php",
"responsive" : true,
"lengthMenu": [10, 25],
"paginationType" : "input",
columns: [
{ data:'param0'},
{ data: 'param1' },
{ data: 'param2' },
{ data: 'param3' },
{ data: 'param4' },
{ data: 'param5' },
{ data: 'param6' },
{ data: 'param7'},
],
"columnDefs": [
{ "visible": false, "targets": [7] }
],
});

You may use visible property of columns.
I suggest enclose object attributes with quotes e.g. "columns", "data" or "visible".
"columns": [
{ "data":'param0'},
{ "data": 'param1', "visible": false},
{ "data": 'param2'},
{ "data": 'param3'},
{ "data": 'param4'},
{ "data": 'param5'},
{ "data": 'param6'},
{ "data": 'param7'},
]

I don't know if you already solved your problem, but since i had the same problem i will share with you at least my solution.
It looks you are using dataTable in Responsive Mode, so based on that, if you want to hide a column you have to apply specific css class for it, based on your need. You apply to the th element associated to the column, and you have your problem solved.
More info about the different css classes can be found here.

I have solved this with some css. Might be helpful for others.
"aoColumnDefs": [
{"sClass": "dt_col_hide", "aTargets": [3]}
],
dt_col_hide is a css class and it will hide column indexed 3 in this case.
.dt_col_hide{display: none;}
or
.dt_col_hide{visibility: hidden;}
as per your requirement.

Related

Jquery Datatables checkbox remember pagination issue

Im using datatables (server side randering) with checkbox plugin from Gyrocode.
var dTable2 = $('table.contracts-search-results').dataTable( {
"processing": true,
"serverSide": true,
"ajax": {
"url": "${someURL}",
"type": "POST",
"data": function (d) {
d.returnEmptyResult = '${returnEmptyResult}';
},
},
searching: false,
"dom": '<"top"iplB<"clear">>rt<"bottom"iplB<"clear">>',
paging: true,
pageLength: 0,
displayStart: 50,
"pagingType": "input",
info: true,
"buttons": [],
"order": [],
"columnDefs":
{"targets": 7,
"width": "75px",
checkboxes: {
"selectRow": true,
"selectAll": false
},
"stateSave": true,
'createdCell': function (td, cellData, rowData, row, col){
var $this = this;
var selectedCon = '${con}';
var arrayOfCon = selectedCon.replace(/[\[\]\s']+/g, '').split(",");
$.map(arrayOfSelectedCon, function(conId, index) {
if(cellData == conId) {
$this.api().cell(td).checkboxes.select();
}
});
},
},
{
"targets": [14, 15, 16],
"visible": false
},
],
"select": {
"style": "multi",
},
"language": {
"decimal": ",",
"thousands": ".",
"url": themeUrl+"js/libs/dataTable/lang/german.json"
},
}
}) ;
I have to pages. On first one I have datatables with configuration posted above. Second page I have another datatables with similar configuration. When user get to second page and choose some rows using checkboxes Im creating list od Ids and when user go back to first page I send Ids from second page to first one and select checkboxes on first page based on Ids from secound page.
The problem is that its working fine If all rows were on the same table page, but when user on secound page used pagination it doesnt work.
use statesave: false as given,
"stateSave": false,

DataTables: createdCell doesn't work on page load (after it works)

I'm using datatables and I'd like to show an icon in a column (based on the value in the column data).
I've written a code like this:
$(document).ready(function() {
var oTable = $("#initiativeTable").DataTable({
"serverSide":true,
"processing":true,
"searching": false,
"ordering": true,
"order": [[ 0, "desc" ]],
"ajax": '${basePath}/cns/initiative/table.json?teams=${teams}&fields=${fields}&search=${search}',
"columns": [
{ "data": "id_init" },{ "data": "parent_name_init" },{ "data": "name_cust" },{ "data": "name_init" },{ "data": "code_paf" },{ "data": "name_team" },{ "data": "pa_name_emp" },{ "data": "pgm_name_emp" },{ "data": "pm_name_emp" },{ "data": "id_initstt" },{ "data": "description_contrtype" },{ "data": "description_inittype" },{ "data": "is_revised_init" }] ,
"columnDefs": [{ "targets": 12,
"createdCell": function (td, cellData, rowData, row, col) {
if ( cellData == 'false' ) {
$(td).html("");
}else{
$(td).html("<span class='glyphicon glyphicon-ok'></span>");
}
}
}
});
});
The DataTables works fine but the column show the value of data, not the icon. If I reorder the table or go on second page of pagination, the createdCell works and the icon is showed.
It doesn't work only on the first load of the page.
What is the problem?
Thanks in advance
Cheers
Matteo
The syntax of createdCell is Inside columns, check columns.createCell:
columns: [
{
data : "name_data",
createCell: function(){
//code
}
}
]
You can use this code:
{
"data": "is_revised_init",
"createdCell": function (td, cellData, rowData, row, col) {
if ( cellData == 'false' ) {
$(td).html("");
}else{
$(td).html("<span class='glyphicon glyphicon-ok'></span>");
}
}
}

Server-based DataTables + YADCF with AJAX-based select2: selecting option clears Select2 selection

The set-up:
DataTables is using remote data with pagination (AJAX-based)
YADCF is using a Select2 that's grabbing options using AJAX call
Selecting Select2 option triggers grid refresh and filtering (everything is correct)
The problem:
Right after DataTables pulls the updated rowset, YADCF re-runs its intialization routine and Select2 loses its state (i.e. the selected option is no longer selected and is not in the DOM anymore).
This:
becomes this after grid reloads (select2 control re-initialized and lost all options pulled via AJAX, including the one that was selected):
How can I avoid YADCF re-initialization in such case?
Having debugged the problem for a while I found that function appendFilters(...) is called after each grid refresh from this YADCF line:
https://github.com/vedmack/yadcf/blob/master/jquery.dataTables.yadcf.js#L3332
which, in turn is fired by DataTables' draw event.
Thanks!
EDIT:
DataTables config array:
var dataTableConfig = {
"autoWidth": false,
"deferLoading": 220,
"pageLength": 5,
"searchDelay": 0,
"searching": true,
"placeholder": null,
"ordering": true,
"paging": true,
"info": true,
"columns": [
{
"name": "company",
"data": {
"_": "company",
"filter": "company",
"display": "company"
},
"visible": true,
"searchable": true,
"orderable": true,
"className": "column_Company"
}
],
"showGlobalSearch": true,
"enableColumnFilter": true,
"columnFilterPosition": "table",
"resetPaging": true,
"select": {
"style": "single"
},
"serverSide": true,
"ajax": {
"url": "/datasource/",
"type": "post"
}
};
YADCF INIT:
colCfg = [
{
"column_number": 2,
"filter_type": "select",
"data": [],
"filter_default_label": "(select..)",
"enable_auto_complete": false,
"sort_as": "alpha",
"sort_order": "asc",
"filter_match_mode": "contains",
"exclude_label": "exclude",
"select_type": "select2",
"select_type_options": {
"width": "300",
ajax: {
url: '/datasource/',
dataType: 'json',
method: 'post',
delay: 750,
data: function (params) {
return {
q: params.term,
page: params.page
};
},
processResults: function (data, params) {
params.page = params.page || 1;
return {
results: data.results,
pagination: {
more: (params.page * 20) < data.total_count
}
};
},
cache: true
},
minimumInputLength: 1,
templateResult: formatItem,
templateSelection: formatItemSelection,
escapeMarkup: function(v) {return v;}
},
"case_insensitive": true,
"filter_delay": 500
}
];
yadcf.init(dataTable, colCfg);

get value of select in cell datatable jquery

I have a datatable with some data. I also add a select element in cells.
$('#tableComponent').dataTable({
"info": false,
"bLengthChange": false, //used to hide the property
"aaData": objJson,
"aoColumns": [{
"mData": "componentID.productID"
}, {
"mData": "componentID.productName"
}, {
"mData": null,
'mRender': function(o) {
return '<select class="form-control"><option value="1">Stock 1</option><option value="2">Stock 2</option></select>';
}
}, {
"mData": "quantity"
}, {
"mData": "unitPrice"
}, {
"mData": "total"
}]
});
And now, I want to get the value of the option that has been selected.
Can you help me resolve this?
Thanks you so much!
You can do something like this
myTable.column(5).nodes().each(function (node, index, dt) {
alert($(myTable.cell(node).node()).find('select.form-control').val());
});
Here is a demo http://jsfiddle.net/dhirajbodicherla/s8JmF/329/
However, for this to work you have to initialize datatables like this
$('#test').DataTable({..});
instead of
$('#test').dataTable({..});
Notice the uppercase D

Example of how to use Kendi UI's Grid with Durandal

I've been messing with this for like 2 days and I just don't get it how to make KendoUI's Grid work with Durandal ie what has to be in the view and what in the viewmodel. I need to fetch the data from a service via Web API but I haven't even got it rendering.
Can anybody please help?
What I did this far:
Viewmodel:
function viewAttached(view) {
var vw = $(view),
grid = $('#pgGrid', vw);
var sampledata = [
{ "ID": 1, "firstName": 'Andrew', "lastName": 'Test' },
{ "ID": 2, "firstName": 'Aidi', "lastName": 'Test' },
{ "ID": 3, "firstName": 'Aiko', "lastName": 'Test' }
];
var pgtemplate = kendo.template($('#pgtemplate', vw).html());
var dataSource = new kendo.data.DataSource({
data: sampledata,
change: function () { // subscribe to the CHANGE event of the data source
$("#pgGrid tbody").html(kendo.render(pgtemplate, this.view())); // populate the table
}
});
dataSource.read();
grid.kendoGrid({
columns: [
{ title: 'ID', field: 'id', width: 40, template: pgtemplate },
{ title: 'First name', field: 'firstName', width: 40, template: pgtemplate },
{ title: 'Last name', field: 'lastName', width: 40, template: pgtemplate }
],
dataSource: dataSource,
editable: false,
pageable: {
refresh: true,
previousNext: false,
numeric: false
},
scrollable: {
virtual: true
},
sortable: false
});
}
And the view:
<div id="pgGrid"
data-kendo-role="grid"
data-kendo-bind="source: gridSource"
data-kendo-editable="true"
data-kendo-columns='["ID",
{ "field": "firstName", "width": "150px" },
{ "field": "lastName", "width": "100px" }]'
data-kendo-pageable="true">
</div>
<script id="pgtemplate" type="text/x-kendo-template">
<tr>
<td>#= id #</td>
<td>#= firstName #</td>
<td>#= lastName #</td>
</tr>
</script>
And I also have set up kendo binding in main.js:
kendo.ns = 'kendo-';
binder.beforeBind = function (obj, view) { kendo.bind(view, obj.viewModel); };
Can anyone please help
Andrew.
Since you are trying to use kendo mvvm to bind the kendo grid (kendo.ns = 'kendo-') you don't have to use jquery to select the grid and render it( grid.kendoGrid({ ) . In your view model just make a property call gridDatasource,
define(function (require) {
return {
gridDatasource:function(){
var sampledata = [
{ "ID": 1, "firstName": 'Andrew', "lastName": 'Test' },
{ "ID": 2, "firstName": 'Aidi', "lastName": 'Test' },
{ "ID": 3, "firstName": 'Aiko', "lastName": 'Test' }
];
var dataSource = new kendo.data.DataSource({
data: sampledata,
change: function () { // subscribe to the CHANGE event of the data source
$("#pgGrid tbody").html(kendo.render(pgtemplate, this.view())); // populate the table
}
});
return dataSource;
}
}
});
And just remove the viewAttached function you don't have to define grid in javascript again since you have defined it in the HTML.
And you can give the row template like this,
<div id="pgGrid"
data-kendo-role="grid"
data-kendo-bind="source: gridSource"
data-kendo-editable="true"
data-kendo-columns='["ID",
{ "field": "firstName", "width": "150px" },
{ "field": "lastName", "width": "100px" }]'
data-kendo-pageable="true"
data-kendo-rowTemplate="pgtemplate"
>
</div>
Knockout Kendo library simplifies this , have a look at this link , also if you use knockout external template you can define the rowTemplate in external file and load it dynamically. Refer this answer about fix for knockout external template when used with durandal