1

I am following this example of how to get elements from a row that is clicked on. This works fine except it does not highlight the selected row. Here is the code:

library(DT)
library(shiny)

runApp(shinyApp(
  ui = fluidPage(DT::dataTableOutput('tab'), verbatimTextOutput('row')),
  server = function(input, output) {
    output$tab = DT::renderDataTable({
      datatable(iris, selection = 'single',
                callback = JS("table.on('click.dt', 'tr',
                                function() {
                                  $(this).toggleClass('selected');
                                  Shiny.onInputChange('row', table.rows('.selected').data().toArray());
                                });")
      )
    })
    output$row = renderText({input$row})
  }
))
Community
  • 1
  • 1
danas.zuokas
  • 4,551
  • 4
  • 29
  • 39

1 Answers1

0

Why not existed in DT input$..._rows_selected ? like

library(shiny)
library(DT)


runApp(shinyApp(
  ui = fluidPage(DT::dataTableOutput('tab'), verbatimTextOutput('row')),
  server = function(input, output) {
    output$tab = DT::renderDataTable({
      datatable(iris, selection = "single"
      )
    })
    output$row = renderText({if(length(input$tab_rows_selected)>0) paste(input$tab_rows_selected,as.character(iris[input$tab_rows_selected,]))})
  }
      ))

Update

for example your have dunamic data

dt1=reactive({
return(iris[iris$Species %in% c("setosa","versicolor"),])})

There may be any other data operation

than your code will be

runApp(shinyApp(
  ui = fluidPage(DT::dataTableOutput('tab'), verbatimTextOutput('row')),
  server = function(input, output) {
    dt1=reactive({
      return(iris[iris$Species %in% c("setosa","versicolor"),])})
    output$tab = DT::renderDataTable({
      datatable(dt1(), selection = "single"
      )
    })
    output$row = renderText({if(length(input$tab_rows_selected)>0) paste(input$tab_rows_selected,as.character(dt1()[input$tab_rows_selected,]))})
  }
      ))

My DT version 0.1.45

Update 2

dont know why but i think $(this).toggleClass('selected'); delete class selected which added in standart DT package(toggleClass used twice and you see nothing) .

try

JS("table.on('click.dt', 'tr',
                              function() {
                                                           Shiny.onInputChange('row', table.rows(this).data().toArray());
                              });")

Or set selection='none'

Batanichek
  • 7,761
  • 31
  • 49