lundi 13 janvier 2020

How to select last options user selected with shiny checkbox group input control

I have found the solution in the first answer to this question (checkboxGroupInput - set minimum and maximum number of selections - ticks) does not work as expected. The reproducible example is as follows:

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)

When selecting checkboxes as you go down the list new selections are added to the tail of the input$SelectedVars vector and thus the tail(input$SelecetedVars,my_max) returns the last three vars the user selected. However as you go back up the list the vars are added to the head of the input$SelectedVars vector so tail(input$SelecetedVars,my_max) continues to return the vars already selected.

My current patch to this is to add a note on my app that says only three vars can be selected at a time. However this relies on the user to understand they have to un-check variables themselves. So for the sake of simplicity I am wondering if there is a way to have the most recent selected var to be appended to the tail of the vector so you can always display the last vars the user selected.




Aucun commentaire:

Enregistrer un commentaire