I have a Shiny app, and I want users to be able to select multiple options--but only up to a certain limit. I can't find a way to limit the numbers.
Below is a simple, reproducible example. In it, I was users to only be able to select up to 2/4 options for the first question, up to 3/4 for the second, and as many as they'd like for the third question (no edits needed for question 3).
library(shiny)
ui <- fluidPage(
sidebarLayout(
sidebarPanel( selectInput("q1", label = "Choose up to 2.", choices = c(" ", "option 1", "option 2", "option 3", "option 4"), multiple = TRUE),
selectInput("q2", label = "Choose up to 3.", choices = c(" ", "option 1", "option 2", "option 3", "option 4"), multiple = TRUE),
selectInput("q3", label = "Choose as many as you want.", choices = c(" ", "option 1", "option 2", "option 3", "option 4"), multiple = TRUE)),
mainPanel(
)
)
)
server <- function(input, output) {
}
# Run the application
shinyApp(ui = ui, server = server)
CodePudding user response:
Instead of selectInput you can use selectizeInput and use the options
argument to set the maximum allowed items using maxItems
.
library(shiny)
ui <- fluidPage(sidebarLayout(
sidebarPanel(
selectizeInput(
"q1",
label = "Choose up to 2.",
choices = c(" ", "option 1", "option 2", "option 3", "option 4"),
multiple = TRUE,
options = list(maxItems = 2)
),
selectizeInput(
"q2",
label = "Choose up to 3.",
choices = c(" ", "option 1", "option 2", "option 3", "option 4"),
multiple = TRUE,
options = list(maxItems = 3)
),
selectInput(
"q3",
label = "Choose as many as you want.",
choices = c(" ", "option 1", "option 2", "option 3", "option 4"),
multiple = TRUE
)
),
mainPanel()
))
server <- function(input, output) {
}
# Run the application
shinyApp(ui = ui, server = server)