firmo23
firmo23

Reputation: 8404

Pre-selection of certain tickboxes in DT::datatable does not work properly as they remain unselected

I have a shiny app in which I want to be able to have the first checkbox selected by default like here. For some reason the first box remains unselected.

#ui.r
navbarPage(
  "Application",
  tabPanel("General",
           sidebarLayout(

             sidebarPanel(
             ),
             mainPanel(
               DT::dataTableOutput("hot5")

             )
           )))
#server.r
library(shiny)
library(DT)
library(tidyverse)
jsfunc <- "function() {arrIndexes=[0]; $('#hot5 tbody tr').filter(function(index) {return arrIndexes.indexOf(index) > -1;}).click()}"

server <- function(input, output,session) {


  output$hot5 <-DT::renderDataTable(
    iris%>% rowid_to_column("Row") %>% mutate(Row = ""),
    rownames = FALSE,
    extensions = "Select",
    options = list(
      initComplete = JS(jsfunc),
      columnDefs = list(list(className = "select-checkbox", targets = 0, orderable = FALSE)),
      select = list(style = "multi", selector = "td:first-child")
    )


  )

}

Upvotes: 0

Views: 42

Answers (1)

St&#233;phane Laurent
St&#233;phane Laurent

Reputation: 84529

You can do as follows:

library(shiny)
library(DT)
library(tibble)

ui <- navbarPage(
  "Application",
  tabPanel("General",
           sidebarLayout(

             sidebarPanel(),

             mainPanel(
               DT::dataTableOutput("hot5")
             )
           )
  )
)

js <- "setTimeout(function(){table.row(0).select()},0)" # I don't know why we need the setTimeout

server <- function(input, output,session) {

  output$hot5 <-DT::renderDataTable({
    datatable(iris%>% rowid_to_column("Row") %>% mutate(Row = ""),
              rownames = FALSE,
              extensions = "Select",
              selection = "none",
              callback = JS(js),
              options = list(
                columnDefs = list(list(className = "select-checkbox", targets = 0, orderable = FALSE)),
                select = list(style = "multi", selector = "td:first-child")
              )
    )
  }, server = FALSE)

}

shinyApp(ui, server)

Upvotes: 1

Related Questions