1
votes

I want two selectInput's in shiny. The first one has a selection with default 'A'. I want the second input value to default based on the value of the first. ie. If the First selection is A, then the default of the second is 'LOW', if the first selection is C or D, the default of the second is 'HIGH'. I need to have the option of the second input to be changed to anything.

I am currently using a selectInput with a uiOutput to link it together, as my code shows. Currently, the default of the second value is always 'LOW', even when I select C or D. I want to be able to select C, and have the second choice default to 'HIGH'

My code:

df=data.frame(expand.grid(col1=LETTERS[1:4],col2=c('LOW','MEDIUM','HIGH')))

ui = fluidPage(
  column(4,
         selectInput('d1','Drop 1',
                     choices = sort(unique(df$col1)),
                     selected = sort(df$col1)[1]),
         uiOutput("secondSelection")
  )
)

server <- function(input, output, session) {
  output$secondSelection = renderUI({
    selectInput("User", "Value Dependent on Drop 1:", 
                choices = as.character(df[df$col1==input$d1,"col2"]))
  }) 
}

shinyApp(ui, server)
1

1 Answers

1
votes

I found a function called updateselectinput, and added it in to fix the problem

df=data.frame(expand.grid(col1=LETTERS[1:4],col2=c('LOW','MEDIUM','HIGH')))

ui = fluidPage(
  column(4,
         selectInput('d1','Drop 1',
                     choices = sort(unique(df$col1)),
                     selected = sort(df$col1)[1]),
         selectInput('d2','Drop 2',
                     choices = sort(unique(df$col2))
                     )
  )
)

server <- function(input, output, session) {

  observe({
    x = input$d1

    if(x=='A'){
      updateSelectInput(session,'d2',
                        choices = sort(unique(df$col2)),
                        selected = 'LOW')
    }else if(x=='C' || x=='D'){
      updateSelectInput(session,'d2',
                        choices = sort(unique(df$col2)),
                        selected = 'HIGH')
    }else{
      updateSelectInput(session,'d2',
                        choices = sort(unique(df$col2)),
                        selected = 'MEDIUM')
    }

  })

}

shinyApp(ui, server)