【问题标题】:How to link checkboxInputs without using radioButtons in Shiny?如何在 Shiny 中不使用单选按钮链接复选框输入?
【发布时间】:2026-02-11 00:10:02
【问题描述】:

我正在尝试在 R Shiny 应用程序中创建两个 checkboxInputs,它们的行为方式是一次只能启用一个,但两者都不启用也应该是一个选项(基本上它们都不能是真的同时)。

ui <- fluidPage(
  checkboxInput("box1", "Test1", value = F),
  checkboxInput("box2", "Test2", value = F)
)

server <- function(input, output, session) {

  observeEvent(input$box1, {

    if (input$box2){
      updateCheckboxInput(session,
                          "box2",
                          value = F)
    }

  })

  observeEvent(input$box2, {

    if (input$box1){
      updateCheckboxInput(session,
                          "box1",
                          value = F)
    }

  })
}

shinyApp(ui = ui, server = server)

上面的应用程序几乎可以执行我想要的,但是选择 @987654323 @ @987654324 @选择 @选择 @987654325 @并取消选择 @987654326 @。 Ideally, when one of the boxes are selected, selecting the other one should disable the former and enable the latter.不使用单选按钮可以吗?

【问题讨论】:

    标签: r shiny


    【解决方案1】:

    您可以通过从 html select only one checkbox in a group 获取 javascript 代码来做到这一点

    所以如果你把checkboxOne.js保存在www目录下:

    $(document).ready(function(){
    
    $("input:checkbox").on('click', function() {
      // in the handler, 'this' refers to the box clicked on
      var $box = $(this);
      if ($box.is(":checked")) {
        // the name of the box is retrieved using the .attr() method
        // as it is assumed and expected to be immutable
        var group = "input:checkbox[name='" + $box.attr("name") + "']";
        // the checked state of the group/box on the other hand will change
        // and the current value is retrieved using .prop() method
        $(group).prop("checked", false);
        $box.prop("checked", true);
      } else {
        $box.prop("checked", false);
      }
    });
    
    });
    
    
    
    ui <- fluidPage(
      tags$head(tags$script(src = "checkboxOne.js"
        )),
    
      checkboxGroupInput("check_box", "Test", choices = c("Test1", "Test2"))
    )
    
    server <- function(input, output, session) {
    
    
    }
    
    shinyApp(ui = ui, server = server)
    

    【讨论】:

      最近更新 更多