checkboxGroupInput - set minimum and maximum number of selections - ticks

时间:2015-06-30 13:36:50

标签: r checkbox shiny

Here is example code with check-box group input:

library(shiny)

server <- function(input, output) {
  output$Selected <- renderText({
    paste(input$SelecetedVars,collapse=",")
  })
}

ui <- fluidPage(
  sidebarLayout(
    sidebarPanel(
      checkboxGroupInput("SelecetedVars", "MyList:",
                         paste0("a",1:5), selected = "a1")
    ),
    mainPanel(textOutput("Selected"))
  )
)

shinyApp(ui = ui, server = server)

enter image description here

As you you can see from image above we can select as many as we want, in this case 4 out of 5.

How can I set minimum and maximum number of ticks? I need minimum of 1 option checked and maximum of 3 options checked. i.e.: prevent unticking the last tick, and prevent ticking when 3 options were already ticked.

2 个答案:

答案 0 :(得分:7)

您可以这样做:

rm(list = ls())
library(shiny)

my_min <- 1
my_max <- 3

ui <- fluidPage(
  sidebarLayout(
    sidebarPanel(
      checkboxGroupInput("SelecetedVars", "MyList:",paste0("a",1:5), selected = "a1")
    ),
    mainPanel(textOutput("Selected"))
  )
)

server <- function(input, output,session) {
  output$Selected <- renderText({
    paste(input$SelecetedVars,collapse=",")
  })

  observe({
    if(length(input$SelecetedVars) > my_max)
    {
      updateCheckboxGroupInput(session, "SelecetedVars", selected= tail(input$SelecetedVars,my_max))
    }
    if(length(input$SelecetedVars) < my_min)
    {
      updateCheckboxGroupInput(session, "SelecetedVars", selected= "a1")
    }
  })
}


shinyApp(ui = ui, server = server)

答案 1 :(得分:1)

您好,您可以使用一点JavaScript来执行此操作:

## In a file named 'js4checkbox.js' in your app folder :
$(document).ready(function(){
  $('input[name=SelecetedVars]').on('click', function(event){
    if($('input[name=SelecetedVars]:checked').length > 3){
      $(this).prop('checked', false);
    }
  });
  $('input[name=SelecetedVars]').on('click', function(event){
    if($('input[name=SelecetedVars]:checked').length == 0){
      $(this).prop('checked', true);
    }
  });
});

ui添加:

fluidPage(
  includeScript(path = "js4checkbox.js"),
  ...
)

我不知道为什么,但它在RStudio Viewer中效果不佳,所以在浏览器中打开它。

对于JS代码,请参阅此post