'Disable / Enable Action Button Based on Condtional Inputs

I would like to make an action button that is enabled only when all applicable inputs are filled. Conversely, if a conditional input is not shown, it should not be required for the action button to be enabled.

library(shiny)
library(shinyjs)

ui <- fluidPage(
  useShinyjs(),
  radioButtons("myRadioButton", label = h4("Input"),
               choices = list("No" = 0,
                              "Yes" = 1),
               selected = character(0)),
  
  conditionalPanel(
    condition = "input.myRadioButton == 1",
    radioButtons("myCondtionalButton", label = h4("Condtional Input"),
               choices = list("A" = 0,
                              "B" = 1,
                              "C" = 2),
               selected = character(0))
  ),
  
  actionButton("submit", "Submit"),
  
  textOutput("myOutput")
)


server <- function(input, output, session){
  
  shinyjs::disable("submit")
  observeEvent({
    input$myRadioButton
    input$myCondtionalButton
    },{
    shinyjs::enable("submit")
  })
  
  score <- reactive({
    if (input$myRadioButton == 1) {
      output <- paste(input$myRadioButton,input$myCondtionalButton)}
    if (input$myRadioButton == 0) {
      output <- input$myRadioButton}
    scoreOut <- output
    })
  
  observeEvent(input$submit, {
    show("myOutput")
    output$myOutput <- renderText({
      paste("This is your value:", score())
    })
  })
  
}

shinyApp(ui, server)

In the above example both "myRadioButton" and "myCondtionalButton" require inputs for the "Sumbit" button to be enabled. I would like to make it so that if "myCondtionalButton" is not shown then only "myRadioButton" is required.



Solution 1:[1]

You can add the following in the server.

observe({
    if (is.null(input$myRadioButton) ) shinyjs::hide("submit")
    else if (input$myRadioButton==1) shinyjs::show("submit")
    else shinyjs::hide("submit")
})

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 YBS