Dynamic selectInput values

I have two selectInputs, one for selecting a device and one for selecting what information they want from that device (temperature, humidity etc). My problem is when I select "Device1" all it's information is shown in the second input, and when I then select "Device2" the second input has the same options even though Device2 might not have that sensor in its database which returns an error.

My code is below:

         selectInput("option", "Device",
                     choices = options()
                     ),
         
         selectInput("dataInput1", "Type",
                     choices = types()
         )

 types <- function() {
   con <- influxdbr::influx_connection(####)
   db_data <- paste0(session$userData$user$username)
   results <- show_field_keys(con, db_data, measurement = input$option)
   results <- results$fieldKey
   return(results)
 }

 options <- function() {
   con <- influxdbr::influx_connection(####)
   query_data <- paste0("SHOW MEASUREMENTS")
   db_data <- paste0(session$userData$user$username)
   results <- show_measurements(con, db_data, where = NULL)
   results <- unname(unlist(results))
   return(results)
 }

My question is how do I have the types from "dataInput1" change depending on what is selected from "option"?

Hi,

The best method to dynamically change input is to use the updateSelectInput function on the server side. Combine this with an observeEvent for the selectInput, and you will be able to fix this. Let me try give an example:

Example app

library(shiny)

ui <- fluidPage(
    #Keep the choices blank, or set the default values
    selectInput("input1", "Input 1",  choices = ""),
    selectInput("input2", "Input 2",  choices = "")
)

server <- function(input, output, session) {
    
    #Will only be run once when initialized, because not in observe event
    #Good thing this way is you can set the choices based on any variable
    updateSelectInput(session, "input1", choices = c("choice1", "choice2"))
    
    #Now change option 2 based on option 1
    observeEvent(input$input1, {
        #Here filter any existing data based on the input1 to get the options for input2
        myChoices = paste(input$input1, "_option_", 1:5, sep = "") #replace with your code
        
        #Update the input 2
        updateSelectInput(session, "input2", choices = myChoices)
    })
    
}

shinyApp(ui = ui, server = server)

Hope this helps!

1 Like

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