javascriptrshinydt

How to select the first row of a datatable when starting a shiny app?


I want to select the first row of the datatable at startup. I am planning to use this JS snippet but not sure if it is correct:

dataTable.row(':eq(0)').select();

Using a callback

It does not work:

library(shiny)
library(DT)

js <- c(
  "table.on('initComplete', function(settings, json) {",
  "  this.row(':eq(0)').select();",
  "  }",
  "});"
)

ui <- fluidPage(
  DTOutput("table")
)


server <- function(input, output, session) {
  output$table <- renderDT({
    datatable(
      mtcars,
      callback = JS(js)
    )
  })
}

shinyApp(ui, server, options = list(
  launch.browser = TRUE
))

Accessing the table on the fly

But I do not know how to find the variable name from my shiny app:

library(shiny)
library(shinyjs)
library(DT)

ui <- fluidPage(
  useShinyjs(),
  DTOutput("table")
)


server <- function(input, output, session) {
  output$table <- renderDT({
    datatable(
      mtcars
    )
  })
  
  ### I need to know the `dataTableVariable`
  runjs("dataTableVariable.row(':eq(0)').select();")
}

shinyApp(ui, server, options = list(
  launch.browser = TRUE
))

Solution

  • Notice that one problem with your callback is that there is one } at the end too much. Using some small modifications, we can pass the callback to the initComplete option of the dataTable, then it will work:

    library(shiny)
    library(DT)
    
    js <- c(
        "function() {",
        "  $(this.api().table().row(':eq(0)').node()).addClass('selected');",
        "}"
    )
    
    ui <- fluidPage(
        DTOutput("table")
    )
    
    
    server <- function(input, output, session) {
        output$table <- renderDT({
            datatable(
                mtcars,
                options = list(
                    initComplete = JS(js)
                )
            )
        })
    }
    
    shinyApp(ui, server)
    

    Another possibility would be to set the definition directly inside the app:

    library(shiny)
    library(DT)
    
    js <- "
    $('#table').on('init.dt', function() {
        $(this).find('tbody tr:first-child').addClass('selected');
    });
    "
    
    ui <- fluidPage(DTOutput("table"),
                    tags$script(JS(js)))
    
    server <- function(input, output, session) {
        output$table <- renderDT({
            datatable(mtcars)
        })
    }
    
    shinyApp(ui, server)