writer_typer
writer_typer

Reputation: 798

How to change the value of actionButton using selectInput?

I'd like to create a situation where actionButton and selectInput influence each other. For example, I'd like to create a situation when the value of the selectInput changes the value of the actionButton.


library(shiny)

ui <- fluidPage(
  sidebarLayout(
    sidebarPanel(
      selectInput("select", "Select Input", choices = c(" ", "A", "B")),
      actionButton("action", "Action Button")
    ),
    mainPanel(
      textOutput("out1"),
      textOutput("out2")
    )
  )
)

server <- function(input, output, session) {
  
  rv <- reactiveValues(count = 0)
  output$out1 <- renderText({
    paste("Action Button: ", input$action)
  })
  
  observeEvent(input$select, {
    if (input$select == "A") rv$count <- rv$count + 1
  })
  
  output$out2 <- renderText({
    paste("Select Input: ", rv$count)
  })
}

options(shiny.autoreload = TRUE)
shinyApp(ui = ui, server = server)

In this example, (thanks to this answer), the values change independently. I've tried to create a common value, but it doesn't seem to update.

I attempted to try updating the value using this updateActionButton(session, "action", "Action Button")

But selectInput does not change the value of the actionButton. I'd like to find a way to make that happen.

Upvotes: 1

Views: 408

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 389235

Why not just use rv$count in Action button text as well?

library(shiny)

ui <- fluidPage(
  sidebarLayout(
    sidebarPanel(
      selectInput("select", "Select Input", choices = c(" ", "A", "B")),
      actionButton("action", "Action Button")
    ),
    mainPanel(
      textOutput("out1"),
      textOutput("out2")
    )
  )
)

server <- function(input, output, session) {
  
  rv <- reactiveValues(count = 0)
  output$out1 <- renderText({
    paste("Action Button: ", rv$count)
  })
  
  observeEvent(input$select, {
    if (input$select == "A") rv$count <- rv$count + 1
  })
  
  output$out2 <- renderText({
    paste("Select Input: ", rv$count)
  })
}

options(shiny.autoreload = TRUE)
shinyApp(ui = ui, server = server)

Upvotes: 1

Related Questions