Trying to change "choices" in selectInput via updateSelectInput

I am trying to change the choices in the second selectInput() based on the choice made in the first selectInput(). Here's is my reprex. Thanks in advance for any help.

library(shiny)
ui <- fluidPage(
  tabPanel("tbls",
    selectInput("tab1",label="Pick a table:",choices=c("a","b","c")),
    selectInput("cht1",label="Pick a time series:",choices=c("d","e","f"))
  )
)
server <- function(input,output,session) {
  Nchoices <- reactive({case_when(
    input$tab1=="a" ~c("d","e","f"),
    input$tab1=="b" ~c("g","h","i"),
    input$tab1=="c" ~c("j","k","l")
  )}) 
  observeEvent(input$tab1,{updateSelectInput(session,input$cht1,
    label="Pick a time series:",choices=Nchoices(),selected=NULL)})
  observe(print(Nchoices()))
}
shinyApp(ui, server)

Philip

below updated version works:

library(shiny)
library(dplyr)

ui <- fluidPage(
  tabPanel("tbls",
           selectInput("tab1",label="Pick a table:",choices=c("a","b","c")),
           selectInput("cht1",label="Pick a time series:",choices=c("d","e","f"))
  )
)
server <- function(input,output,session) {
  Nchoices <- reactive({case_when(
    input$tab1=="a" ~c("d","e","f"),
    input$tab1=="b" ~c("g","h","i"),
    input$tab1=="c" ~c("j","k","l")
  )}) 
  observeEvent(input$tab1,{updateSelectInput(session, 'cht1',
                                             label="Pick a time series:",choices=Nchoices(),selected=NULL)}) 
  observe(print(Nchoices()))
}
shinyApp(ui, server)

pay attenion to the inputId argument of updateSelectInput(), should be cht1, not input$cht1

1 Like

Thank you for this solution.

I see now that I have another problem. I want the new choices to be larger or smaller in number. In my reprex, the third set of choices should include "m" as c("j","k","l","m"). When I include a different number of choices, the code breaks again. Any help appreciated.

Philip

A generic fix would be wrap the c() values inside of list, and later unlist them

  Nchoices <- reactive({
    case_when(
    input$tab1=="a" ~list(c("d","e","f")),
    input$tab1=="b" ~list(c("g","h","i")),
    input$tab1=="c" ~list(c("j","k","l","m"))
  )}) 
    updateSelectInput(session, 'cht1',
                      label="Pick a time series:",
                      choices=unlist(Nchoices()),
                      selected=NULL)})
2 Likes

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.