简体   繁体   中英

Shiny: Getting info from the selected row in a DT data table

We are trying to recreate example: https://demo.shinyapps.io/029-row-selection/ , using the DT package for rendering the data frame instead of the shiny package. DT::Datatable also has the 'callback' option but it doesn't seem to work when using the same javascriptcode as in the demo.

our current code:

    shinyServer(function(input, output) {
      output$tbl <- DT::renderDataTable(
       DT::datatable(mtcars,options = list(pageLength = 10, 
        callback = JS("function(table) {
                                         table.on('click.dt', 'tr', function() {
                                         $(this).toggleClass('selected');
                                         Shiny.onInputChange('rows',
                                         table.rows('.selected').indexes     ().toArray());
                                         });
    }")
    ))
   )

    output$rows_out <- renderText({
      paste(c('You selected these rows on the page:', rows),
          collapse = ' ')
    })
  })

Does anyone knows how to achieve this?

Many thanks in advance, Thomas

PS: In the following example we found how to color columns in a datatable: renderDataTable Select all cells containing value > 10 and highlight

Ok I found the solution. This is working, few more work is needed to clean up the output, but I think we have 90% done. Max

library(shiny)
library(DT)
shinyApp(
    ui = fluidPage(dataTableOutput('foo'),textOutput('rows_out')),
    server = function(input, output) {
        output$foo = renderDataTable({
            datatable(iris, 
                callback = JS(
                    "table.on('click.dt', 'tr', function() {
                                            $(this).toggleClass('selected');
                        Shiny.onInputChange('rows',
                        table.rows('.selected').data().toArray());
                                        });")
            )
        })
        output$rows_out =renderText({

            paste(c('You selected these rows on the page:', input$rows),
                  collapse = ' ')
        })
    }

)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM