DataTables API row().data() - javascript

Hi everybody and happy new year :)
So, I use dataTables library. In their web site i found this example, where function must return the row of table, which was clicked.
var table = $('#example').DataTable();
$('#example tbody').on( 'click', 'tr', function () {
console.log( table.row( this ).data() );
} );
I try use this example for my code, but i have the error
Uncaught TypeError: aucTable.row is not a function
my code:
var mainTable = $('#mainTable');
$(document).ready(function () {
mainTable.dataTable({
'searching': false,
'ajax': 'assets/static_data/data.json',
'columns': [
{
title: "Name",
data: "name"
},
{
title: "Office",
data: "office"
},
{
title: "Extn.",
data: "extn"
},
{
title: "Salary",
data: "salary"
},
{
title: "Start date",
data: "start_date"
},
{
title: "Details",
data: null,
defaultContent: "<button class='details-btn btn'>More details</button>",
sorting: false
}
]
});
});
$('#mainTable').on('click', '.details-btn', function () {
var selectedRow = aucTable.row(this).data();
console.log(selectedRow);
$("<div id='details-dialog'/>").dialog({
modal: true,
show: true,
maxWidth: 620,
maxHeight: 300,
minWidth: 500,
minHeight: 200,
title: "Hello World"
});
});
Can somebody tell me, why I have this error? And why i can't get the row, which was clicked?
Tanks for everybody.
Best regard and have fun.

I'm not familiar with datatables, however you might try changing it to the following:
var mainTable = null;
$(document).ready(function () {
mainTable = $('#mainTable').dataTable({...});
});
$('#mainTable').on('click', '.details-btn', function () {
var tr = $(this).closest('tr');
var selectedRow = mainTable.row(tr).data();
console.log(selectedRow);
//...
});
Note that I'm storing the result to the $('#mainTable').dataTable() call in the mainTable variable so that you can reference it later when calling the row() function.
The other thing to note is that in your click handler, it looks like you need to find the tr from the datatable - calling mainTable.row(this) does not yield a row because this is the button that was clicked, not the row of the table.
See this link for an example that seems similar to what you're doing.

In the current code, the acuTable var not exist. So you can change your code in order to have an acuTable var pointing to the datatable instance, something like:
var mainTable = $('#mainTable');
var acuTable;
$(document).ready(function () {
acuTable = mainTable.dataTable({
'searching': false,
'ajax': 'assets/static_data/data.json',
'columns': [
{
title: "Name",
data: "name"
},
{
title: "Office",
data: "office"
},
{
title: "Extn.",
data: "extn"
},
{
title: "Salary",
data: "salary"
},
{
title: "Start date",
data: "start_date"
},
{
title: "Details",
data: null,
defaultContent: "<button class='details-btn btn'>More details</button>",
sorting: false
}
]
});
});
$('#mainTable').on('click', '.details-btn', function () {
var selectedRow = aucTable.row(this).data();
console.log(selectedRow);
$("<div id='details-dialog'/>").dialog({
modal: true,
show: true,
maxWidth: 620,
maxHeight: 300,
minWidth: 500,
minHeight: 200,
title: "Hello World"
});
});

Related

How do I change floatingFilter option after Init of AGGrid?

I'm using AgGrid with JavaScript module. I'm trying to change the value of floatingFilter after init of Grid by calling api.refreshHeader method but it's not working.
function getServices() {
var columnDefs = [
{ field: 'name', headerName: 'Name' },
{ field: 'Category', headerName: 'Category' },
];
var gridOptions = {
animateRows: true,
columnDefs: columnDefs,
defaultColDef: {
resizable: true,
filter: true,
sortable: true,
flex: 1,
},
floatingFilter: true, // I want to change this after init
};
var gridDiv = document.querySelector('#serviceGrid');
var gridInstance = new agGrid.Grid(gridDiv, gridOptions);
$.ajax({
type: 'GET',
dataType:"JSON",
url: 'FROM_URL',
success:function(data){
gridOptions.api.setRowData(data)
}
});
// For testing purpose I'm using timeout
setTimeout(function() {
gridInstance.gridOptions.floatingFilter = false;
gridInstance.gridOptions.api.refreshHeader();
}, 5000)
}
Correct me if I'm wrong anywhere.
I am not sure which version you are using, but in the latest version, floatingFilters go inside columnDefinitions and not inside gridOptions.
Move floatingFilters inside defaultColDef in your gridOptions.
var gridOptions = {
animateRows: true,
columnDefs: columnDefs,
defaultColDef: {
resizable: true,
filter: true,
sortable: true,
flex: 1,
floatingFilter: true, // I want to change this after init
},
};
and then change your setTimeout function to this.
// For testing purpose I'm using timeout
setTimeout(function() {
gridInstance.gridOptions.defaultColDef.floatingFilter = false;
gridInstance.gridOptions.api.refreshHeader();
}, 5000)
Here is a plnkr I forked from one of their examples that works.
Hope I was able to help.

Hide a button in jquery based on user access

I'm trying to hide a button. If it was on the html i would simply do
<security:authorize access="hasAuthority('Administrator')">
//html button code
</security:authorize>
but my delete button is being generated from datatable.
var table = $('#dataTable').DataTable({
language: {
searchPlaceholder: "Search...",
emptyTable: "There are no available flows."
},
columnDefs: [ {
orderable: false,
className: 'select-checkbox',
targets: 0
},
{type: "date-euro", targets: 7},
{type: "date-euro", targets: 8}
],
order: [[1, 'desc']],
select: {
style: 'multi',
selector: 'td:first-child'
},
lengthChange: false,
dom: 'Bfrtip',
buttons: [
{
text: '<span class="fa fa-plus"></span> Create',
className: 'btn-primary-outline',
action: function () {
location.href = "create-flow";
}
},
{
text: '<span class="fa fa-trash"></span> Delete',
className: 'btn-danger-outline',
action: function () {
console.log($('#hasAuthority').val());
var selectedRows = table.rows({selected: true});
if (selectedRows.nodes().length > 0) {
//Get names
var data = selectedRows.data();
var names = [];
$.each(data, function (index, value) {
names.push(value[2]);
});
//Remove them
$.ajax({
url: '/flow/delete?names=' + names,
type: 'delete',
success: function () {
//reload page
location.reload();
}
});
//de-select selected rows
table.rows('.selected').deselect();
}
}
}
]
});
I'm trying to give a value to a input if user is admin or not but I'm getting undefined
<security:authorize access="hasAuthority('Administrator')" var="hasAuthority"></security:authorize>
<input type="hidden" id="hasAuthority" value="${hasAuthority}">
But then how do I corporate the if(hasAuthority) only on the delete button? The syntax doesn't match.

jquery datatable - set column width and wrap text

We are using the Scroller plugin for our jquery data table to allow virtual scrolling. However, we have requirement to support text wrapping inside a cell, as user would like to view the entire text instead of truncated one. I observed that it does not wrap the text by default. Is there a way to support this feature? Any possible workaround?
Fiddler
https://jsfiddle.net/Vimalan/2koex0bt/1/
html Code:
<table id="example" class="display" cellspacing="0" width="100%"></table>
js code:
var detailsSample = "DataTables and its extensions are extremely configurable libraries and almost every aspect of the enhancements they make to HTML tables can be customised. Features can be enabled, disabled or customised to meet your exact needs for your table implementations."
var dataList = [];
for (var i=1; i<=500; i++)
{
var dataRow = {};
dataRow.ID = i;
dataRow.FirstName = "First Name " + i;
dataRow.LastName = "Last Name " + i;
if (i%5 ==0)
{
dataRow.Details = detailsSample;
}
else
{
dataRow.Details = "Large text "+i;
}
dataRow.Country = "Country Name";
dataList.push(dataRow);
}
$('#example').DataTable( {
data: dataList,
deferRender: true,
scrollX: true,
scrollY: 200,
scrollCollapse: true,
scroller: true,
searching: false,
paging: true,
info: false,
columns: [
{ title: "ID", data: "ID" },
{ title: "First Name", data: "FirstName" },
{ title: "Change Summary", data: "LastName"},
{ title: "Details", data: "Details", "width": "400px" },
{ title: "Country", data: "Country" }
]
} );
Expectation
In the above table, the "Details" column should always have a width of 400px and the text in that column should wrap.
Any suggestion will be greatly appreciated.
Found the solution by wrapping the column data in a div and setting the white-space, width css properties for the div.
Fiddler:https://jsfiddle.net/Vimalan/2koex0bt/6/
JS
$('#example').DataTable( {
data: dataList,
deferRender: true,
scrollX: true,
scrollY: 200,
scrollCollapse: true,
scroller: true,
searching: false,
paging: true,
info: false,
columns: [
{ title: "ID", data: "ID" },
{ title: "First Name", data: "FirstName" },
{ title: "Change Summary", data: "LastName"},
{ title: "Details", data: "Details" },
{ title: "Country", data: "Country" }
],
columnDefs: [
{
render: function (data, type, full, meta) {
return "<div class='text-wrap width-200'>" + data + "</div>";
},
targets: 3
}
]
} );
CSS
.text-wrap{
white-space:normal;
}
.width-200{
width:200px;
}
Not sure if you add in stylesheets or not, but set your table-layout to fixed and add in the white-space. Currently you are using white-space:no-wrap which negates what you're trying to do. Also I set a max-width to all your td's so this will happen whenever there is overflow.
Add this at the end of your jQUery
https://jsfiddle.net/2koex0bt/5/
$(document).ready(function(){
$('#example').DataTable();
$('#example td').css('white-space','initial');
});
If you want to just use the api, do this ( add in anymore CSS to change the styling ).
If you want to do it with CSS, do this:
table {
table-layout:fixed;
}
table td {
word-wrap: break-word;
max-width: 400px;
}
#example td {
white-space:inherit;
}
Js Code:
'columnDefs': [{
render: function (data, type, full, meta) {
let instaText = (data != null && data.length > 25) ? data.substr(0, 25) : data == null?"":data;
return '<div class="text-overflow" title='+'"'+ data +'"' +'>' + instaText + '</div>';
},
targets: [27]
}],
CSS:
{
overflow: hidden;
text-overflow: ellipsis;
max-width: 80%;
}

onUnselect event of jquery easyui datagrid

I am using JQuery EasyUI 1.3.4, I am having some trouble catching onUnselect event, following code illustrates my problem:
function NavigateProcess() {
$(function () {
var data = list;
$('#dg').datagrid({
view: detailview,
cache: true,
data: data,
loadMsg: 'Processing, please wait …',
singleSelect: true,
columns: [[
{
title: 'Name', field: 'Name', width: 180, editor: 'text'
//,formatter: formatProgress
},
{ field: 'ID', title: 'ID', width: 60, align: 'right', editor: 'text' },
{ field: 'RatePlan', title: 'RatePlan', width: 80, editor: 'text' },
{ field: 'ActivationDate', title: 'ActivationDate', width: 80, editor: 'text' },
{ field: 'DataType', title: 'DataType', hidden: 'true' }
]],
onUnselect: function (rowIndex, rowData) {
alert('unselect');
if (lastselectedrow) {
$('#dg').datagrid('endEdit', lastselectedrow);
}
},
onSelect: function (rowIndex, rowData) {
alert('select');
lastselectedrow = rowIndex;
$('#dg').datagrid('beginEdit', rowIndex);
},
detailFormatter: function (index, row) {
return '<div style="padding:1px"><table id="ddv-' + index + '"></table></div>';
}
});
});
function doSearch() {
$('#tt').datagrid('load', {
itemid: $('#itemid').val(),
productid: $('#productid').val()
});
}
}
I put two alert statements in onSelect and onUnselect events, onSelect is triggered when I click on a row. Since singleSelect property is true, selecting another row will result in an onUnselect and onSelect events, at least that's my understanding. When I click on rows only onSelect alert pops up, alert of onUnselect never pops up, can somebody point me how to capture onUnselect event? Any help will be appreciated.
there is an inherent bug that prevents invoking onUnselect event

How to change grid column value on DataBound event

I have the following Grid,
<div class="kotgrid">
</div>
And I bound the data as following. Here I want to change timedelay column value on DataBound event,
$(".kotgrid").kendoGrid({
dataSource: dataSource,
dataBound: function (e) {
var grid = this;
grid.tbody.find('>tr').each(function () {
var dataItem = grid.dataItem(this);
var d = new Date();
var currentTime = parseTime(dataItem.servertime);
var currenTime = d.getHours() + ":" + d.getMinutes();
var meanTime = diff(orderTime2, currenTime2)
//I want to set this meanTime in timedelay coloumn. How can I achieve this?
})
},
filterable: true,
scrollable: true,
columns: [
{ hidden: true, field: "orderitemid" },
{ field: "tableid", title: "Table No" },
{ field: "itemname", title: "Items" },
{ field: "quantity", title: "Quantity" },
{ field: "modifier", title: "Modifier" },
{ hidden: true, field: "orderedtime", title: "Time Delay" },
{ field: "timedelay", title: "Time Delay" },
{ hidden: true, field: "alert" },
{ hidden: true, field: "category", groupHeaderTemplate: "#= value #" },
{ command: { text: "Pickup", click: showDetails} }
],
mobile: "phone",
editable: false,
selectable: "row",
height: "600px"
});
I don't know how to achieve it. Any help will be highly appreciable.
Thanks in advance.
You don't need to iterate over the <tr> elements, unless you only want to do it for the current page. You can just iterate over grid.dataSource.data().
So you could do something like:
var data = this.dataSource.data();
$(data).each(function() {
var d = new Date();
var currentTime = parseTime(this.servertime);
var currenTime = d.getHours() + ":" + d.getMinutes();
var meanTime = diff(orderTime2, currenTime2)
// set on dataItem
this.set("timedelay", meanTime);
});
Regardless of how you get access to the dataItem, you can set any property using the set method (the data source contains Model items which inherit from ObservableObject).

Categories