Graham
Graham

Reputation: 176

R shiny: Remove dynamically 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 2 or more options from the selectizeInput function.

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, checkboxGroupInput("selected_Numbers", 'Chosen Number(s)', choices = c(),selected=c('')))
)

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()))
    })
  })
  
  observe({
    updateCheckboxGroupInput(session, "selected_Numbers", choices = unique(c(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))
  })
  
  
}

shinyApp(ui, server)

Help appreciated in helping clear all unselected choices. Thank you

Upvotes: 0

Views: 118

Answers (1)

HubertL
HubertL

Reputation: 19544

In this case it seems easier to use renderUI() to rebuild the checkboxGroupInput.

In UI :

  column(width = 4, uiOutput("my_checkboxGroupInput"))

In Server :

  output$my_checkboxGroupInput <- renderUI(
    checkboxGroupInput("selected_Numbers", 'Chosen Number(s)', 
                       choices = unique(lvl()),selected=lvl()))
  

Upvotes: 1

Related Questions