简体   繁体   中英

Detecting a selectInput value change to NULL in R Shiny

In the code below, I cannot detect selectInput 's value change to NULL

library(shiny)
ui <- fluidPage(
  selectInput(
    inputId = "var",
    label = "Select a variable:",
    choices = c("A", "B", "C"),
    selected = NULL,
    multiple = T),
  textOutput("selected_var")
)
server <- function(input, output) {
  observeEvent(input$var, {
    showNotification("var changed")
    output$selected_var <- renderPrint(paste0("selected var: ", input$var))
    if(is.null(input$var)) {                          # I want to be able to
      showNotification("var changed to null")         # detect this action
    }
  })
}
shinyApp(ui = ui, server = server)

If a user were to choose A then press the backspace to delete it, I want to be able to detect that action.

How would you detect the value of input$var changing to NULL ?

By default observeEvent is set to ignore NULL . Adding ignoreNULL = FALSE to observeEvent will fix that. You may also wish to add ignoreInit = TRUE to stop the observeEvent from triggering on startup.

Here is the full code:

library(shiny)

ui <- fluidPage(

    selectInput(inputId = "var", label = "Select a variable:", choices = c("A", "B", "C"), selected = NULL, multiple = T),

    textOutput("selected_var")

)

server <- function(input, output) {

    observeEvent(input$var, {

        if(is.null(input$var)) {    

            showNotification("var changed to null")    

        }

    }, ignoreInit = TRUE, ignoreNULL = FALSE)

}
shinyApp(ui = ui, server = server)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM