sredemption
sredemption

Reputation: 145

How to pre-select rows in Shiny DT datatables

I'm using Shiny (0.12.0) with DT (0.0.65) for row-selections in this Shiny datatable. I want to pre-select the first 5 rows. I have tried:

callback JS:

output$x1 = DT::renderDataTable({
    datatable(cars,
        rows = $("#x1 tbody tr");
        $(rows).slice(0,5).each(function() {
            $(this).click();
        });
    )
})

Upvotes: 14

Views: 7481

Answers (2)

Duncan Ellis
Duncan Ellis

Reputation: 346

If you want to bind a reactive to the selected input, here's a quick example of how that might be done.

I've modified the client side example above to add a selectInput that allows you to dynamically choose which row to highlight. It would be trivial to extend this to a multi-select scenario.

library(shiny)
if (packageVersion('DT') < '0.1.3') devtools::install_github('rstudio/DT')
library(DT)
shinyApp(
  ui = fluidPage(
    fluidRow(
      shiny::selectInput("myrow", "Select Row", choices = seq(nrow(iris))),
      h1('Client-side processing'),
      DT::dataTableOutput('x1'),
      h1('Server-side processing'),
      DT::dataTableOutput('x2')
    )
  ),
  server = function(input, output, session) {

    myselected <- shiny::reactive(as.integer(input$myrow))

    output$x1 = DT::renderDataTable(
      iris, server = FALSE,
      selection = list(mode = 'multiple', selected = myselected())
    )
    output$x2 = DT::renderDataTable(
      iris, server = TRUE,
      selection = list(mode = 'multiple', selected = rownames(iris)[c(1, 3, 8, 12)])
    )
  }
)

Upvotes: 0

Yihui Xie
Yihui Xie

Reputation: 30114

This feature has been added to DT (>= 0.1.3). Examples:

library(shiny)
if (packageVersion('DT') < '0.1.3') devtools::install_github('rstudio/DT')
library(DT)
shinyApp(
  ui = fluidPage(
    fluidRow(
      h1('Client-side processing'),
      DT::dataTableOutput('x1'),
      h1('Server-side processing'),
      DT::dataTableOutput('x2')
    )
  ),
  server = function(input, output, session) {
    output$x1 = DT::renderDataTable(
      iris, server = FALSE,
      selection = list(mode = 'multiple', selected = c(1, 3, 8, 12))
    )
    output$x2 = DT::renderDataTable(
      iris, server = TRUE,
      selection = list(mode = 'multiple', selected = rownames(iris)[c(1, 3, 8, 12)])
    )
  }
)

Upvotes: 19

Related Questions