checkboxGroupInput - set minimum and maximum number of selections - ticks

偶尔善良 提交于 2020-03-18 04:54:33

问题


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)

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.


回答1:


You can do something like this:

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)



回答2:


Hello you can use a little JavaScript to do it :

## 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);
    }
  });
});

And in your ui add :

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

I don't know why but it doesn't work well in the RStudio Viewer so open it in your browser.

For the JS code see this post



来源:https://stackoverflow.com/questions/31139791/checkboxgroupinput-set-minimum-and-maximum-number-of-selections-ticks

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!