Search code examples
rshinyshinyjs

disable downloadButton when no shiny checkboxGroupInput item selected


I would like the download button in the below shiny app to become enabled ONLY when at least one check box is selected. Following this guidance, the below app disables the button upon page load and enables the download button after the user selects a check box. However, if the user then deselects all checkboxes, the button remains enabled. Is there a way to program the app to disable the download button again if the user deselects all checkboxes?

library(shiny)
data(iris)

ui <- fluidPage(
  
  shinyjs::useShinyjs(),
  
  mainPanel(
    fluidRow(checkboxGroupInput(inputId = "iris_species", label = "Select Species", 
        choices = unique(iris$Species))),
    fluidRow(downloadButton("download_bttn" , "Download Artifact"))
  )
)

server <- function(input, output) {
  
  observe({
    if(!is.null(input$iris_species)) {
      shinyjs::enable("download_bttn")
    }
  })
  
  output$download_bttn <- downloadHandler(filename = function(){paste0("Artifact -",Sys.Date(),".csv") },
    content = function(file) {
      
      iris_mod <- iris[which(iris$Species %in% input$iris_species),]
      write.csv(iris_mod, file)
   }
  )

  # disable the download button on page load
  shinyjs::disable("download_bttn")  
  
}

shinyApp(ui = ui, server = server)


Solution

  • In your observe, you need to know to disable it as well. You can use an else clause with disable, or you can just use

      observe({
        shinyjs::toggleState("download_bttn", condition = !is.null(input$iris_species))
      })
    

    in place of your current observe block.