How do you render a boolean true/false value coming from JSON to a green check or a red x on a jquery datatable?
For example, something like:
✓
✓
and
✗
✗
Using bootstrap glyphicons you can do this:
personTable = $("#person-table").DataTable({
order: [1, "desc"],
"autoWidth": false,
ajax: {
url: uri,
dataSrc: "",
},
"columns": [
{ "data": "FirstName", "title": "Name" },
{ "data": "Address", "title": "Address" },
{ "data": "IsActive", "title": "Active" }
],
"columnDefs": [
{
"render": function (data, type, row) {
return row.FirstName + " " + row.LastName;
},
"targets": 1
},
{
"render": function (data, type, row) {
return (data === true) ? '<span class="glyphicon glyphicon-ok"></span>' : '<span class="glyphicon glyphicon-remove"></span>';
},
"targets": 2
}
]
});
Then add some css like this:
/* Green check. */
.glyphicon-ok {
color: green;
}
/* Red X. */
.glyphicon-remove {
color: red;
}
For my purposes I am ok with adding this custom CSS to a pre-defined bootstrap icon. If you don't want that, define and use your own class.
Related
I have a JQuery DataTable. Fpr each row I have a button and when the user clicks on it, it should show related fields in a modal in order to edit that row. Now my problem is I can't get the selected row id and it returns undefined. Here is my code:
$("#myDummyTable").DataTable({
"processing": true, // for show progress bar
"serverSide": true, // for process server side
"filter": true, // this is for disable filter (search box)
"orderMulti": false,
//"searching": false,
"language": {
"url": "/language/Persian.json"
},
"ajax": {
"url": "Data/GetData",
"type": "POST",
"datatype": "jason"
},
"columnDefs": [{
"targets": [0],
"visible": false,
"searchable": false
}],
rowId: "id",
"columns": [
{ "data": "id", "name": "Id", "autoWidth": true },
{ "data": "startDate", "name": "StartDate", "autoWidth": true },
{ "data": "endDate", "name": "EndDate", "autoWidth": true },
{
defaultContent: '<input type="button" class="Edit" value="edit"/>
}
]
});
$('#myDummyTable tbody').on('click', '.Edit', function () {
var row = myDummyTable.row(this).rowId;
var myDummyTable = $('#myDummyTable').DataTable();
console.log('row:' + myDummyTable.row(this).rowId);
});
});
Instead of using the defaultContent column option, you can use a render function. This allows you to customize each button so it can include the relevant ID:
{ data: "id", render: function ( data, type, row, meta ) {
return '<input type="button" class="Edit" id="' + data + '" value="edit id ' + data + '"/>';
}
}
Here we first use data: id again (same as for the first column). This means this column will use the id value.
Then we use the render function which gives us access to the id value via the data variable.
In my example I added the ID to the text used by each button.
I also added an id attribute to each of these cells, using the same data value. This assumes each ID is unique, of course.
My test data - an example of one row:
{
"id": "5",
"name": "Airi Satou",
"start_date": "2008/11/28",
"office": "Tokyo"
}
In this case, Airi Satou's ID is 5.
My test table:
Now, when I click on a button, the following code will print the related ID:
$('#myDummyTable tbody').on('click', '.Edit', function () {
console.log( this.id );
});
I want to get the selected checkbox value from the data table, in my table, I have two columns and the first one is for the checkbox and the second one is for display values.
Here is just returning a checkbox. How can we know that there is a click that happens?
Help me.
Here is the code
function BindColumSelectTable(DataExchangeList) {
debugger
$('#columnSelectTable').DataTable({
"data": DataExchangeList,
"destroy": true,
"columns": [
{
data: 'check', render: function (data, type, row) {
debugger;
return '<input type="checkbox"/>'
}
},
{ data:"FieldCaption" },
],
"columnDefs": [
{
orderable: false,
className: "select-checkbox",
targets:0
},
{ className:"tabletdAdjust","targets":[1]}
],
});}
I'm using jquery data table
function BindColumSelectTable(DataExchangeList) {
$('#columnSelectTable').DataTable({
"data": DataExchangeList,
"destroy": true,
"columns": [
{
data: 'check', render: function (data, type, row) {
var checkbox = $("<input/>",{
"type": "checkbox"
});
if(data === "1"){
checkbox.attr("checked", "checked");
checkbox.addClass("checked");
}else{
checkbox.addClass("unchecked");
}
return checkbox.prop("outerHTML")
}
},
{ data:"FieldCaption" },
],
"columnDefs": [
{
orderable: false,
className: "select-checkbox",
targets:0
},
{ className:"tabletdAdjust","targets":[1]}
],
});}
Try this
Here is the answer I use onclick function for each click it will trigger the function
function BindColumSelectTable(DataExchangeList) {
debugger
$('#columnSelectTable').DataTable({
"data": DataExchangeList,
"destroy": true,
"columns": [
{
data: 'ColumnCheck', render: function (data, type, row) {
debugger;
return '<input type="checkbox" onclick="ColumnCheck(this)"/>'
}
},
{ data:"FieldCaption" },
],
"columnDefs": [
{
orderable: false,
className: "select-checkbox",
targets:0
},
{ className:"tabletdAdjust","targets":[1]}
],
});
}
the above code is the same i used in the question only one thing i added is an onclick function
and the onclick function is
function ColumnCheck(thisObj) {
debugger;
var dataExchangeCheckColumnVM = $('#columnSelectTable').DataTable().row($(thisObj).parents('tr')).data();
var dataExchangeCheckColumnList = $('#columnSelectTable').DataTable().rows().data();
for (var i = 0; i < dataExchangeCheckColumnList.length; i++) {
if (dataExchangeCheckColumnList[i].FieldCaption !== null) {
if (dataExchangeCheckColumnList[i].FieldCaption === dataExchangeCheckColumnVM.FieldCaption) {
dataExchangeCheckColumnList[i].ColumnCheck = thisObj.checked;
}
}
}
_dataExchangeColumnList = dataExchangeCheckColumnList;
}
so i used an property **ColumnCheck ** it is boolean variable. on each iteration it will added a true value if check box is checked
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>");
}
}
}
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.
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