1

How to observe when any of the multiple buttons is clicked? For example, we have three buttons, I would like to show the notification when any of the buttons is clicked. Here is an example code

library(shiny)


ui <- fluidPage(
  actionButton('button1', 'button1'),actionButton('button2', 'button2'),actionButton('button3', 'button3'))

server <- function(input, output, session) {
  
  
  
  
  
  observe({
    
    req(input$button1, input$button2, input$button3)
    
    
    showNotification("This is a notification.")
    
    
    
  })
}

shinyApp(ui, server)

The above code is not satisfactory because when initiate the page, only when three buttons are all clicked, notification shows.

Also, is it possible to know which button is cliecked?

Thanks.

Tan
  • 157
  • 5
  • Look at [Get the event which is fired in Shiny](https://stackoverflow.com/a/56771353/10489562). – phili_b Jul 07 '21 at 22:12

3 Answers3

3

Use observeEvent instead and put all your triggers in c()

library(shiny)


ui <- fluidPage(
    actionButton('button1', 'button1'),actionButton('button2', 'button2'),actionButton('button3', 'button3'))
server <- function(input, output, session) {
    observeEvent(c(input$button1, input$button2, input$button3), ignoreInit = TRUE, {
        showNotification("This is a notification.")
    })
}

shinyApp(ui, server)
lz100
  • 6,990
  • 6
  • 29
0

Convert input to a list and use it as your trigger object for an observeEvent:

observeEvent(reactiveValuesToList(input),{
  #do something
})
Victor Burnett
  • 588
  • 6
  • 10
0

Some alternative ways of doing this:

library(shiny)
library(purrr)

ui <- fluidPage(
  actionButton('button1', 'button1'),actionButton('button2', 'button2'),actionButton('button3', 'button3'))

server <- function(input, output, session) {
  
  paste0('button', 1:3) %>% 
  map(~ observeEvent(input[[.x]], {
    showNotification("This is the general notification.")
    showNotification(paste(.x, 'pressed'))
  }))
  
  
}

shinyApp(ui, server)

or using only observe():

library(shiny)
library(stringr)
library(purrr)

ui <- fluidPage(
  actionButton('button1', 'button1'),actionButton('button2', 'button2'),actionButton('button3', 'button3'))

server <- function(input, output, session) {
  observe({
    nms <- str_subset(names(input), 'button')
    if ( any(map_lgl(nms,~ input[[.x]] != 0)) ) {
      
      showNotification("This is a notification.")
      
    } 
  })
}

shinyApp(ui, server)
jpdugo17
  • 6,816
  • 2
  • 11
  • 23