How to tell a multiple selection is empty?

shiny

#1

I want to hide the button when the multi-selection is empty, but I can’t figure out how to make it work.
Any hint would be greatly appreciated!
Thanks!

library(shinyjs)
app <- shinyApp(
  ui = bootstrapPage(
    useShinyjs(),
    selectInput("sInput", "Select:", choices=1:4, multiple = TRUE),
    verbatimTextOutput("vOutput"),
    actionButton("btn", "A button")
  ),
  server = function(input, output) {
    observeEvent(input$sInput, {
      output$vOutput = renderText(input$sInput)
      if(is.null(input$sInput))
        hide(id = "btn") else
          show(id = "btn")
    })
  }
)
runApp(app)

#2

One way to do it is by placing the button inside a conditional panel. The other way is by using the toggle function from shinyjs package as below. You can read more here.

library(shiny)
library(shinyjs)
app <- shinyApp(
  ui = bootstrapPage(
    useShinyjs(),
    selectInput("sInput", "Select:", choices=1:4, multiple = TRUE),
    verbatimTextOutput("vOutput"),
    actionButton("btn", "A button")
  ),
  server = function(input, output) {
    observeEvent(input$sInput, {
      output$vOutput = renderText(input$sInput)
    })
    
    observe({ toggle(id="btn", condition=!is.null(input$sInput))})
  }
)
runApp(app)

#3

Great! It works! Thank you!
However, I can not understand why observeEnvent can not detect the change when the last element of selectInput is removed, while observe can see the change.
Is it a bug of observeEnvent?
Thanks!

By the way, it also works (it should) when I put hide and show inside observe.

library(shiny)
library(shinyjs)
app <- shinyApp(
  ui = bootstrapPage(
    useShinyjs(),
    selectInput("sInput", "Select:", choices=1:4, multiple = TRUE),
    verbatimTextOutput("vOutput"),
    actionButton("btn", "A button")
  ),
  server = function(input, output) {
    observeEvent(input$sInput, {
      output$vOutput = renderText(input$sInput)
    })
    observe({
      if(is.null(input$sInput))
        hide(id = "btn") else
          show(id = "btn")
    })
  }
)
runApp(app)

#4

I can’t tell if this is a bug, but I think an observeEvent produces a result that can be used as an input to other reactive expressions. A show/hide button is not that kind of result.


#5

It’s not a bug. observeEvent() has an argument ignoreNULL which is TRUE by default. When it’s true, it will ignore the value when it is NULL. When the select input is empty, its value returns NULL, so the observeEvent doesn’t get triggered. If you want to trigger it even on NULLs, then you can add ignoreNULL = FALSE


#6

Thanks @daattali! I did not noticed this argument before.