You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Shiny中基于单选按钮动态更新selectizeInput选项的实现方法

Shiny 单选按钮联动更新 selectizeInput 实现方案

你原有代码存在两处笔误:一是 updateSelectizeInput 调用时指定的输入ID和UI中定义的species_selector不一致,二是误用了不存在的变量names_vectors。修正笔误后,在更新组件时添加selected = ""配置即可实现切换时清空已有选中值的需求,完整可运行代码如下:

library(shiny)
library(shinyWidgets)

names_vector1 = paste0("common", 1:10)
names_vector2 = paste0("scientific", 1:10)

ui = fluidPage(
  fluidRow(
    selectizeInput(
      inputId = "species_selector",
      label = "Choose a species:",
      selected = "common1",
      choices = c("Choose" = "", names_vector1),
      options = list(
        maxOptions = 5,
        maxItems = 4
      )
    ),
    awesomeRadio(
      inputId = "species_selector_type",
      label = NULL,
      choices = c("Common name","Scientific name"),
      selected = "Common name",
      inline = TRUE
    )
  )
)

server = function(input, output, session){
  # 监听名称类型单选按钮变化
  observeEvent(input$species_selector_type, {
    # 匹配当前对应的选项列表
    target_choices <- if(input$species_selector_type == "Scientific name") {
      names_vector2
    } else {
      names_vector1
    }
    # 更新selectizeInput,selected设为空清空已有选中内容
    updateSelectizeInput(
      session,
      inputId = "species_selector",
      choices = c("Choose" = "", target_choices),
      selected = ""
    )
  })
}

shinyApp(ui, server)

实现逻辑说明:

  • 仅监听单选按钮的取值变化事件,触发更新逻辑
  • 每次切换名称类型时,自动匹配对应名称向量作为下拉选项
  • 更新组件时指定selected = "",会自动清空用户之前的选中内容,符合需求

内容的提问来源于stack exchange,提问作者Tom__Jenkins

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 01:39:03