简体   繁体   中英

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.

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")
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM