Home > Back-end >  observeEvent listen to any input with same name pattern
observeEvent listen to any input with same name pattern

Time:06-03

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 reprex, 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)

CodePudding user response:

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)
  • Related