限制 shinyWidgets 包中 multiInput() 中选定项目的数量

Limit number selected items in multiInput() from shinyWidgets package

假设我有以下 Shiny 应用程序 -

library(shinyWidgets); library("shiny")
ui <- fluidPage(
  multiInput(
    inputId = "id", label = "Fruits :",
     choices = c("Banana", "Blueberry", "Cherry",
                "Coconut", "Grapefruit", "Kiwi",
                "Lemon", "Lime", "Mango", "Orange",
                "Papaya"),
    selected = "Banana", width = "400px",
     options = list(
       enable_search = FALSE,
       non_selected_header = "Choose between:",
      selected_header = "You have selected:"
    )
   ),
   verbatimTextOutput(outputId = "res")
 )

 server <- function(input, output, session) {
   output$res <- renderPrint({
     input$id
  })
 }

shinyApp(ui = ui, server = server)

现在我想用户可以选择的项目数量上限 3。有什么办法可以用multiInput()实现这个吗?

是的,您可以通过在选项列表中指定来提供限制:

ui <- fluidPage(
  multiInput(
    inputId = "id", label = "Fruits :",
     choices = c("Banana", "Blueberry", "Cherry",
                "Coconut", "Grapefruit", "Kiwi",
                "Lemon", "Lime", "Mango", "Orange",
                "Papaya"),
    selected = "Banana", width = "400px",
     options = list(
       limit = 3,
       enable_search = FALSE,
       non_selected_header = "Choose between:",
      selected_header = "You have selected:"
    )
   ),
   verbatimTextOutput(outputId = "res")
 )