Determine if DT datatable will be pressed in a brilliant application

Here is a working example of my best attempt to get a 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 it observeEventonly responds if the user clicks on a cell that is different from the previously pressed one. Is there a way to get an event in any table?

+4
source share
1 answer

I think it might be useful.

Try adding callbackwith Shiny.onInputChange and add smth, which has changed all the 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 we analyze everything rowand colfrominput$rows

PS. in the datatables index start at 0.

+2
source

All Articles