1

I have a Shiny app with many inputs with similar id. There's one action that any of them should trigger. I need to dinamically refer to those input ids inside an observeEvent listener. The number of inputs is unknown, so I need a general solution. I tried to name the input with a regex, but I didn't manage to make it work. Here's an example app:

library(shiny)

ui <- fluidPage(
  actionButton("button_1", label = "Button 1"),
  actionButton("button_2", label = "Button 2"),
  actionButton("button_3", label = "Button 3")
)

server <- function(input, output, session) {
  
  observeEvent((input$button_1|input$button_2|input$button_3),  { #Replace with listen to any input with id starting with "button_"
    showModal(modalDialog("Thanks for pushing the button"))
  })
 }

shinyApp(ui, server)
David Jorquera
  • 2,046
  • 12
  • 35
  • 1
    Check out [this answer](https://stackoverflow.com/a/58884438/3460670) - would this work? – Ben Jun 03 '22 at 00:48
  • 1
    Yes! however, it has the same problem as my example app: the event is triggered at start. You know what could be causing that? – David Jorquera Jun 03 '22 at 01:19
  • 2
    I found the answer! To not trigger at start add `ignoreInit = TRUE` to the `observeEvent()` function. – guasi Jun 03 '22 at 03:01

2 Answers2

2

I made this work for a number of buttons that you would define in the eventExpr of the observeEvent

library(shiny)

ui <- fluidPage(
  actionButton("button_1", label = "Button 1"),
  actionButton("button_2", label = "Button 2"),
  actionButton("button_3", label = "Button 3")
)

server <- function(input, output, session) {
  
  observeEvent(
    eventExpr = {
      buttons <- paste0("button_",1:10)
      list_of_buttons = NULL
      for(var in buttons) {
        list_of_buttons <- append(list_of_buttons, input[[var]])
      }
      list_of_buttons
  }, 
    handlerExpr = { #Replace with listen to any input with id starting with "button_"
      showModal(modalDialog("Thanks for pushing the button"))
  }, 
  ignoreInit = T
)}

shinyApp(ui, server)
guasi
  • 1,461
  • 3
  • 12
2

For dynamic number of buttons you could use

library(shiny)

ui <- fluidPage(
  actionButton("button_1", label = "Button 1"),
  actionButton("button_2", label = "Button 2"),
  actionButton("button_3", label = "Button 3")
)

server <- function(input, output, session) {
  
  observeEvent(
    lapply(
      names(input)[grep("button_[0-9]+",names(input))],
      function(name){input[[name]]}),  {
        showModal(modalDialog("Thanks for pushing the button"))
  }, ignoreInit = TRUE)
  
}

shinyApp(ui, server)
YBS
  • 19,324
  • 2
  • 9
  • 27
  • @Ben linked this [solution by Victor Burnett](https://stackoverflow.com/questions/34157684/dynamic-number-of-actionbuttons-tied-to-unique-observeevent/58884438#58884438) already. – guasi Jun 03 '22 at 13:38