Reputation: 1430
In rCharts, one can set JS callbacks of DataTables using a special string notation: #! function(par) {...} !#
. For example, let's look into the following R code:
#JS callback to truncate long strings in table cells and add a tooltip
callback = "#!
function (nRow) {
$('td', nRow).each(function (index) {
var maxChars = 80;
var unfilteredText = $(this).text();
if (unfilteredText.length > maxChars && maxChars > 3) {
$(this).attr('title', unfilteredText);
$(this).html(unfilteredText.substring(0, maxChars-4) + '...');
}
});
return nRow;
} !#"
result <- dTable(df, aaSorting = list(c(5, "desc")), sPaginationType="full_numbers",
fnRowCallback=callback)
Is this possible in Shiny DataTables?
Upvotes: 4
Views: 2473
Reputation: 6776
I just stumbled across this question and was able to use the information here, along with help from section 4.5 of this post to solve this problem. In order to get this to work, you would simply do the following:
library(DT)
long_strings = replicate(10, paste(sample(c(0:9, letters, LETTERS), 135, replace = TRUE), collapse = ""))
dat <- data.frame(x = 1:10,
y = month.abb[1:10],
z = long_strings,
stringsAsFactors = FALSE)
DT::datatable(dat,
options = list(
rowCallback = JS("function(row, data) {",
" var max_chars = 80, full_text = data[3];",
" if (full_text.length > max_chars) {",
" $('td:eq(3)', row).attr('title', full_text);",
" $('td:eq(3)', row).html(full_text.substring(0, max_chars - 4) + '...');",
" }",
"}")))
It's important to note that since we want this to operate on a per row basis, we use the rowCallback
function inside of the options
parameter. This is in contrast to the callback
function that can be used on the entire table, which is its own parameter for DT::datatable
.
Also take note of the fact that you don't have to call .text()
or .innerHTML
or anything of that sort on data[3]
. The value that is returned is the text value of that cell.
Hopefully someone in the future stumbles across this and finds it beneficial.
Upvotes: 2