Bear
Bear

Reputation: 680

Require input to be selected for pickerInput

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?

Upvotes: 0

Views: 1463

Answers (1)

Pork Chop
Pork Chop

Reputation: 29387

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)

Upvotes: 2

Related Questions