问题
Here is a working example of my best attempt to get table click event:
library(shiny)
library(DT)
runApp(shinyApp(
ui = fluidPage(DT::dataTableOutput('table')),
server = function(input, output, session) {
output$table <- DT::renderDataTable({
dt <- data.frame(a = 1)
datatable(dt, rownames = FALSE, selection = 'none')
})
observeEvent(input$table_cell_clicked, {
print(Sys.time())
})}
))
The problem is that observeEvent
reacts only if user clicks on the cell which differs from previously clicked. Is there a way to get event on any table click?
回答1:
I think it s may be helpful
Try add callback
with Shiny.onInputChange
and add smth which changed all time ( rnd
)
smt like
JS("table.on('click.dt', 'td', function() {
var row_=table.cell(this).index().row;
var col=table.cell(this).index().column;
var rnd= Math.random();
var data = [row_, col, rnd];
Shiny.onInputChange('rows',data );
});")
and then use it like :
library(shiny)
library(DT)
runApp(shinyApp(
ui = fluidPage(DT::dataTableOutput('table')),
server = function(input, output, session) {
output$table <- DT::renderDataTable({
datatable(data.frame(a = c(1,2),b=c(2,3)), rownames = FALSE, selection = 'none', callback = JS("table.on('click.dt', 'td', function() {
var row_=table.cell(this).index().row;
var col=table.cell(this).index().column;
var rnd= Math.random();
var data = [row_, col, rnd];
Shiny.onInputChange('rows',data );
});")
)}
)
observeEvent(input$rows, {
print(input$rows)
print(Sys.time())
})}
))
Then parse all row
and col
from input$rows
PS. in datatables index start from 0 .
来源:https://stackoverflow.com/questions/36132730/determine-if-dt-datatable-is-clicked-in-shiny-app