R Shiny如何强制用户从两个pickerInput累计选择至少5个选项
解决方案
核心调整说明
- 新增响应式逻辑统计
list_1、list_2两个pickerInput的累计选中数量,同时合并所有选中的机构名称 - 增加条件判断分支:累计选中数量≥5时输出所有选中内容,不足则输出指定提示文本
- 修复原代码中输入ID引用错误的问题:原代码错误引用
input$list1/input$list2,实际组件注册的ID为list_1/list_2
完整可运行代码
# LIBRARIES ---- library(shiny) library(shinyWidgets) # USER INTERFACE ---- ui <- fluidPage( sidebarLayout( sidebarPanel = sidebarPanel( width = 4, p("Peer Group Comparisons"), pickerInput( inputId = "list_1", label = "Organizations from List 1", choices = c("a", "b", "c", "d"), options = pickerOptions( actionsBox = TRUE, liveSearch = TRUE), multiple = TRUE ), pickerInput( inputId = "list_2", label = "Organizations from List 2", choices = c("e", "f", "g", "h", "x", "y", "z"), options = pickerOptions( actionsBox = TRUE, liveSearch = TRUE), multiple = TRUE ) ), mainPanel = mainPanel( width = 8, textOutput("results") ) ) ) # SERVER ---- server <- function(input, output, session) { # 响应式获取选中项和总数量 selected_data <- reactive({ s1 <- input$list_1 s2 <- input$list_2 all_selected <- c(s1, s2) return( list( count = length(all_selected), orgs = all_selected ) ) }) output$results <- renderText({ sel <- selected_data() if (sel$count >= 5) { paste0("已选中的机构:", paste(sel$orgs, collapse = "、")) } else { "请至少选择5个机构才可继续操作!" } }) } shinyApp(ui, server)
内容的提问来源于stack exchange,提问作者Ahmad Mobin
相关产品推荐
相关产品推荐

