Graham
Graham

Reputation: 176

R shiny: Remove render UI created checkboxGroupInput upon deselection

I am trying to create a set of checkboxGroupInput choices that when deselected disappear. I am able to do this for selected choices of 2 or more. However, upon deselection of the final choice, it persists unselected rather than disappearing.

Please see the following, selecting options from the selectizeInput function.

In the server, it is important that the original UI selected and choices remain separate from the updateCheckboxGroupInput selected and choices functions as these are initially retrieved from persistent data storage that can then be manipulated.

library(shiny)

ui <- fluidPage(
  
  column(width = 4, align = "left", uiOutput("choose_Number")),
  br(),
  column(width = 4, align = "left", div(
    align = "left", 
    actionButton('add', 'Confirm Number(s)', style="color: #fff; background-color: #53C1BE"))
  ),
  column(width = 4, uiOutput("my_checkboxGroupInput"))
)

server <- function(input, output, session) {
  
  output$choose_Number <- renderUI({
    selectizeInput("choose_Number", "Choose Number(s)", as.list(c(1:4)), options=list(create=TRUE,'plugins' = list('remove_button'),
                                                                                      persist = FALSE), multiple = TRUE)
  })
  
  
  lvl<-reactive(unlist(input$selected_Numbers))
  
  observe({
    if(input$add==0) return()
    isolate({
      current_selection<-paste(input$choose_Number,sep=", ")
      updateCheckboxGroupInput(session, "selected_Numbers", choices = c(current_selection,lvl())
                               ,selected=c(current_selection,lvl()))
    })
  })
  
  observeEvent(input$selected_Numbers,({
    updateCheckboxGroupInput(session, "selected_Numbers", choices = unique(as.list(lvl()))
                             ,selected=c(lvl()))
  })
  )
  
  observeEvent(input$add, {
    updateSelectizeInput(session, "choose_Number", choices = as.list(1:4), 
                         selected = character(0),
                         options = list(create=TRUE, 'plugins' = list('remove_button'), persist = FALSE))
  })
  
  output$my_checkboxGroupInput <- renderUI(
    checkboxGroupInput("selected_Numbers", 'Chosen Number(s)', 
                       choices = c(1,2,3),selected= c(1,2,3)))
  
  
}

shinyApp(ui, server)

Help appreciated in helping clear all unselected choices. Thank you

Upvotes: 0

Views: 126

Answers (1)

YBS
YBS

Reputation: 21297

If your choices is a list it works as desired. Try this

observe({
    updateCheckboxGroupInput(session, "selected_Numbers", choices = unique(as.list(lvl()))
                             ,selected=c(lvl()))
  })

Upvotes: 1

Related Questions