1

I am trying to create two checkboxInputs in an R Shiny app which behave in a way that only one can be enabled at a time but having neither enabled should also be an option (essentially they both can't be true at the same time).

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)

The above app almost does what I want but selecting box2 when box1 is selected just disables both of them instead of selecting box2 and unselecting box1. Ideally, when one of the boxes are selected, selecting the other one should disable the former and enable the latter. Is this possible without using radioButtons?

ANam
  • 337
  • 2
  • 15

1 Answers1

0

You can do this by sourcing the javascript code from html select only one checkbox in a group

So if you save checkboxOne.js under www directory:

$(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)
MKa
  • 2,248
  • 16
  • 22