In my Shiny app, I want to include a selectInput in a DT datatable and allow selection of multiple options. This renders fine with multiple = F
, but with multiple = T
, the selection doesn't display or work properly. Please see example below. When "Multiple" is unselected, the selectInput renders fine in the table, but when it is selected, the selectInput is not rendered properly. Any suggestions?
Update: I modified the code to include a selectInput by itself with multiple = TRUE
to show what I expect it to look like in the table. Specifically, in the table, there is no field above the dropdown with the selections displayed and I am unable to select multiple choices. Also see screenshot.
require(shiny)
require(DT)
shinyApp(
ui = fluidPage(
checkboxInput(inputId = "multiple", label = "Multiple", value = F),
selectInput(inputId = "expected", label = "Expected", choices = letters, multiple = T),
DT::dataTableOutput("mytable")
),
server = function(input, output, session) {
output$mytable <- DT::renderDataTable({
if(is.null(input$multiple)) return()
DT::datatable(
data = data.frame(
Col1 = c(
as.character(selectInput(
inputId = "id1",
label = NULL,
choices = letters,
multiple = input$multiple
))
)
),
escape = F,
selection = "none"
)
})
}
)
Update 2: Thanks to @Jamie for a great solution. I was able to modify that solution when I need multiple selectInputs in my table and want the same desired format. See below:
require(shiny)
require(DT)
SelectizeIDs <- function(ids) {
myStrings <- as.character(sapply(ids, function(id) {
paste0(" $('#", id, "').selectize();")
}))
c(
"function(settings){",
myStrings,
"}"
)
}
shinyApp(
ui = fluidPage(
checkboxInput(inputId = "multiple", label = "Multiple", value = F),
selectInput(inputId = "expected", label = "Expected", choices = letters, multiple = T),
DT::dataTableOutput("mytable")
),
server = function(input, output, session) {
output$mytable <- DT::renderDataTable({
DT::datatable(
data = data.frame(
Col1 = c(
as.character(selectInput(
inputId = "id1",
label = NULL,
choices = letters,
multiple = input$multiple
)),
as.character(selectInput(
inputId = "id2",
label = NULL,
choices = letters,
multiple = input$multiple
))
)
),
escape = F,
selection = "none",
options = list(
ordering = F,
initComplete = JS(SelectizeIDs(c("id1", "id2"))),
preDrawCallback = JS('function(){Shiny.unbindAll(this.api().table().node());}'),
drawCallback = JS('function(){Shiny.bindAll(this.api().table().node());}')
)
)
})
}
)
CodePudding user response:
Here's an option where I leaned heavily from this question.