r - 当 multiple 为 true 时,如何限制用户可以使用 R Shiny 的 selectInput 选择的选项数量?

标签 r shiny shinydashboard selectinput

我有一个 Shiny 应用程序,我希望用户能够选择多个选项 - 但只能达到一定的限制。我找不到限制数量的方法。

下面是一个简单的、可重现的示例。在其中,我的用户只能为第一个问题选择最多 2/4 个选项,为第二个问题选择最多 3/4 个选项,为第三个问题选择任意数量的选项(问题无需编辑) 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)

最佳答案

您可以使用 selectizeInput 代替 selectInput,并使用 options 参数使用 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)

关于r - 当 multiple 为 true 时,如何限制用户可以使用 R Shiny 的 selectInput 选择的选项数量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69317783/

相关文章:

r - updateTabItems 的问题。在 R 中与 Golem 一起 Shiny

r - 在 tabItems Shiny 仪表板之间切换

r - ShinyDashboard 动态要点

r - 字符串公式(来自 paste())不适用于 randomForest()

当某些列在 R 中具有某些值时删除某些列

r - 在 R Shiny 输入中按 Enter 键选择多个搜索关键字项目

r - 使用 Shiny R 将 react 性弹出图/图添加到 Leaflet map

r - 部署时如何指定要使用的 Shiny 帐户?

regex - 删除转义\n

r - 实时监控文件更改