Search code examples
javascriptrshiny

Shiny does not detect shiny:inputchanged event


The approach I am taking for my shiny app design would be easiest if the app could detect the ID of the last clicked or updated widget.

This question appears to solve the problem. However, when I run the MCVE with the accepted answer I get no reactivity at all.

Current code as follows. This is essentially the linked question with the obvious substitution made from the accepted answer.

library(shiny)

ui <- fluidPage(
  tags$head(
    # taken from accepted answer
    tags$script(
      HTML("$(document).on('shiny:inputchanged', function(event) {
          Shiny.setInputValue('last_input', event.name);
        });")
    )
    # through to here
  ),
  
  numericInput("num1", "Numeric", 0),
  textInput("text1", "Text"),
  selectInput("select1", "Select", choices = LETTERS[1:4]),
  selectInput("selectize1", "Selectize", choices = letters[1:4]),
  
  textOutput("textout")
)

server <- function(input, output, session) {
  output$textout <- renderText({
    input$last_input
  })
}

shinyApp(ui, server)

Expected behavior:

  • When the widgets are interacted with, then the id of the last widget interacted with is displayed.

Observed behavior:

  • Regardless of which widget I interact with, no widget ids are displayed.

Checked tried:

  • Updating Shiny version.
  • The other code suggestions on the original post - no change
  • Some, but not full, reactivity from using ....ready(function(){$('input').on('shiny:inputchanged'... instead of just .on('shiny:inputchanged'.

I am an R, not a JS, programmer. Can someone with both skills can advise how to get this working?


Solution

  • You need to exclude the input, which is set in the JS part regarding the events to monitor, otherwise you'll end up in an endless loop.

    Please check my related answer here:

    library(shiny)
    
    ui <- fluidPage(
      tags$head(
        tags$script(
          "$(document).on('shiny:inputchanged', function(event) {
              if (event.name != 'changed') {
                Shiny.setInputValue('changed', event.name);
              }
            });"
        )
      ),
      numericInput("num1", "Numeric", 0),
      textInput("text1", "Text"),
      selectInput("select1", "Select", choices = LETTERS[1:4]),
      selectInput("selectize1", "Selectize", choices = letters[1:4]),
      
      textOutput("textout")
    )
    
    server <- function(input, output, session) {
      output$textout <- renderText({
        input$changed
      })
    }
    
    shinyApp(ui, server)
    

    Here the according documentation can be found.