rshinydtshinywidgetspickerinput

shinyWidgets pickerInput in DT datatable with liveSearch


I would like to insert pickerInputs from shinyWidgets in a DT datatable in a Shiny app. However, the liveSearch option is not working for me when rendered inside a datatable. Also, when I have a separate pickerInput outside of the datatable (uncomment the pickerInput line inside fluidPage() below), the pickerInputs inside the table do not render. I would appreciate help getting this to work.

library(shiny)
library(DT)
library(shinyWidgets)

shinyApp(
  ui = fluidPage(
    # pickerInput(inputId = "test", label = "Test", choices = c("option1", "option2")),
    DT::dataTableOutput("mytable")
  ),
  server = function(input, output, session) {
    df <- data.frame(
      col1 = as.character(pickerInput(
        inputId = "Picker",
        choices = c("option1", "option2", "option3", "zebra"),
        options = pickerOptions(liveSearch = T)
      ))
    )
    output$mytable <- DT::renderDataTable({
      DT::datatable(
        data = df,
        escape = F
      ) 
    })
  }
)

Solution

  • One solution is to put the DT table directly in the UI:

    library(shiny)
    library(DT)
    library(shinyWidgets)
    
    df <- data.frame(
      col1 = as.character(pickerInput(
        inputId = "Picker",
        label = "Picker",
        choices = c("option1", "option2", "option3", "zebra"),
        options = pickerOptions(liveSearch = TRUE)
      ))
    )
    
    shinyApp(
      ui = fluidPage(
        
        pickerInput(
          inputId = "test", 
          label = "Test", 
          choices = c("option1", "option2"),
          options = pickerOptions(liveSearch = TRUE)
        ),
        
        datatable(
          data = df,
          escape = F
        )
      ),
      server = function(input, output, session) { }
    )
    

    Note that you have to put another picker input (such as the "test" one) in the UI, in order that JavaScript dependencies are loaded. If you don't want this picker input, you can hide it with some CSS (display: none;).

    enter image description here


    Edit: in the server

    library(shiny)
    library(DT)
    library(shinyWidgets)
    
    shinyApp(
      ui = fluidPage(
        pickerInput(inputId = "test", label = "Test", choices = c("option1", "option2")),
        DTOutput("mytable")
      ),
      server = function(input, output, session) {
        df <- data.frame(
          col1 = as.character(pickerInput(
            inputId = "myPicker",
            choices = c("option1", "option2", "option3", "zebra"),
            options = pickerOptions(liveSearch = TRUE)
          ))
        )
        output$mytable <- renderDT({
          datatable(
            data = df,
            escape = FALSE,
            options = list(
              initComplete = JS('function() { $("#myPicker").selectpicker(); }')
            )
          ) 
        })
      }
    )