Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine if DT datatable is clicked in shiny app

Tags:

r

dt

shiny

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?

like image 489
danas.zuokas Avatar asked Mar 21 '16 13:03

danas.zuokas


1 Answers

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 .

like image 195
Batanichek Avatar answered Nov 19 '22 06:11

Batanichek