Home > Software engineering >  Detect changes in the value of shiny inputs
Detect changes in the value of shiny inputs

Time:09-15

I have a shiny app where I would like to get the change in a select input compared to the last selection.

For example in this app, three months are initially selected. January February March If a user selects April, I would like to see the change between the initial selection and the current selection.

**Initial selection:**
January February March

**Current selection:**
January February March April
library(shiny)
library(shinydashboard)
library(htmltools)

ui <- fluidPage(
  inputPanel(
    
    selectInput("months", label = "Select Months", 
                choices = c(month.name[]), selected = month.name[1:3], 
                multiple = TRUE)),
  
  strong("Initial selection:"), textOutput("initial_selection"), br(),
  strong("Current selection:"), textOutput("current_selection")
  
)

server <- function(input, output) {
  
  ## Initial selection (should stay the same for one additional change)
  output$initial_selection <- renderText({ input$months })
  
  ## Current selection (after the change)
  output$current_selection <- renderText({ input$months })
}

shinyApp(ui, server)

I tried a few random methods but with no success. Any help will be much appreciated.

Cheers,

CodePudding user response:

Is this what you're looking for? I am going to create a counter in the reactiveValues so we can monitor the changes, first when it is 0, we shall record the initial selections, then we can use the counter for the new changes...

library(shiny)
library(shinydashboard)
library(htmltools)

ui <- fluidPage(
  inputPanel(
    
    selectInput("months", label = "Select Months", 
                choices = c(month.name[]), selected = month.name[1:3], 
                multiple = TRUE)),
  
  strong("Initial selection:"), textOutput("initial_selection"), br(),
  strong("Current selection:"), textOutput("current_selection")
  
)

server <- function(input, output) {
  
  v <- reactiveValues(count = 0,initial_selection = NULL,current_selection=NULL)
  
  observeEvent(input$months,{
    if(v$count==0){
      v$initial_selection <- input$months
      v$current_selection <- input$months
    }else{
      v$current_selection <- input$months
    }
    v$count <- v$count   1
  })
  

  ## Initial selection (should stay the same for one additional change)
  output$initial_selection <- renderText({
    v$initial_selection
  })
  
  ## Current selection (after the change)
  output$current_selection <- renderText({ 
    v$current_selection 
  })
}

shinyApp(ui, server)

enter image description here

  • Related