Within my Shiny application, I have implemented a DT datatable that includes selectInputs which are dynamically updated based on user input. To enhance the styling and search functionality of these selectInputs, I have utilized JavaScript to bind/unbind and selectize them. Instead of using shiny::updateSelectInput(), I opted for DT::datatableProxy() and DT::replaceData() methods to update the selectInputs within the datatable. This decision was made due to the dynamic nature of my application, where selectInputs can be added or removed based on user interactions.
However, I am facing a minor issue. Upon initial rendering, the selectInputs display the desired selectized style. Yet, after a user-triggered update to the table and selectInputs, the selectized styling is lost.
I am seeking guidance on how to retain the selectized style when both the table and selectInputs are updated simultaneously.
library(shiny)
library(DT)
# Selectize input ids
selectize_ids <- function(ids) {
tmp <- paste0(" $('#", ids, "')")
tmp <- paste0(tmp, ".selectize();")
c(
"function(settings){",
tmp,
"}"
)
}
shinyApp(
ui = fluidPage(
div(style = "display: none;", selectInput(inputId = "dummy", label = NULL, choices = 1:2)),
actionButton(inputId = "my_button", label = "Click Me"),
DT::dataTableOutput(outputId = "table")
),
server = function(input, output, session) {
input_ids <- c("A_1", "A_2")
df_reactive <- reactive({
data.frame(
A = sapply(input_ids, function(id) as.character(selectInput(
inputId = id,
label = NULL,
choices = paste0(c("a", "b", "c"), input$my_button)
)))
)
})
output$table <- DT::renderDataTable({
DT::datatable(
data = isolate(df_reactive()),
selection = "none",
rownames = F,
escape = F,
options = list(
initComplete = JS(selectize_ids(input_ids)),
preDrawCallback = JS('function() { Shiny.unbindAll(this.api().table().node()); }'),
drawCallback = JS('function() { Shiny.bindAll(this.api().table().node()); } ')
)
)
})
proxy <- DT::dataTableProxy(outputId = "table")
observe({
DT::replaceData(proxy = proxy, data = df_reactive(), rownames = F)
})
}
)