Determine if DT datatable is clicked in shiny app

坚强是说给别人听的谎言 提交于 2019-12-09 06:51:05

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!