0

How can I require that a user selects an input from a pickerInput?

Here is a basic example:

library("shiny")
library("shinyWidgets")

ui <- fluidPage(
  column(
    width = 4,
      pickerInput(inputId = "fruit", 
                  label = "Fruits", 
                  choices = c("Apple", "Mango", "Pear", "Orange"),
                  options = list(`actions-box` = T, 
                                 `none-selected-text` = "Please make a selection!"),
                  multiple = T)
        ))
server <- function(input, output) {
   output$res <- renderPrint({
   input$fruit
   })
}

shinyApp(ui = ui, server = server)

Is there an option I can add when I create the pickerInput menu that sets it so that the menu will always require input?

2
  • 1
    req(input$fruit) might help as the first line inside output$res.
    – r2evans
    Oct 23, 2018 at 16:16
  • You could just have a selected= inside the pickerInput that way it initializes on a choice, therefore no choice is not an option?
    – Chabo
    Oct 23, 2018 at 16:24

1 Answer 1

1

You can simply update it, we can also add a popup indicating that at least 1 elements has to be selected

library("shiny")
library("shinyWidgets")

mychoices <- c("Apple", "Mango", "Pear", "Orange")

ui <- fluidPage(
  column(
    width = 4,
    pickerInput(inputId = "fruit", 
                label = "Fruits", 
                choices = mychoices,
                options = list(`actions-box` = T, `none-selected-text` = "Please make a selection!",selected = mychoices[1]),
                multiple = T)
  ),
  column(4,textOutput("res"))

)
server <- function(input, output,session) {

  data <- eventReactive(input$fruit,{
    if(is.null(input$fruit)){
      updatePickerInput(session,"fruit",choices = mychoices,selected = mychoices[1])
      showNotification("At least 1 should be selected", duration = 2,type = c("error"))
    }
    input$fruit
  },ignoreNULL = F)

  output$res <- renderPrint({
    req(data())
    data()
  })
}

shinyApp(ui = ui, server = server)
2
  • If I am reading this properly it tells the user they need to select a value but then chooses the first value as a default?
    – Bear
    Oct 23, 2018 at 17:05
  • What if I just wanted to re-ask the User to pick instead of default picking something. In my full code I use the UI to read in a file so I can't default to any value (unless I default to All values).
    – Bear
    Oct 24, 2018 at 18:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.