Reputation: 172
I am building a shiny
web page with a form made up of two selectInput
: the first one - static - in the ui
section and the second one - dynamic - in the server
section. A simplification of the real issue is shown below.
require(shiny)
ui <- fluidPage(
# The static input
selectInput(inputId = 'static',
label = 'Make a choice',
choices = c('A', 'B', 'C'),
selectize = FALSE),
# The dynamic input
uiOutput(outputId = 'dynamicInput'),
# The output
hr(),
strong('This is a check for the output:'),
textOutput(outputId = 'check')
)
server <- function(input, output, session) {
# The dynamic input definition
output$dynamicInput <- renderUI({
# This input exists if the `static`
# one is equal to `A` only
if (input$static == 'A') {
selectInput(inputId = 'dynamic',
label = 'Choose a subset for `A`',
choices = c('A1', 'A2', 'A3'),
selectize = FALSE)
} else {
return(NULL)
}
})
# The example output
output$check <- renderText({
paste(input$static, input$dynamic)
})
}
shinyApp(ui, server)
In the real case I have to launch a query on a database based on the static input and, eventually, the dynamic one (if exists).
When testing the app I correctly got the dynamic selectInput
at the first round and I am able to select - lets' say - the A2
option. Then, if I choose B
in the static selectInput
, the dynamic input is not responsive and still shows the previous selection instead of showing NULL
.
How can I force the dynamic selectInput
to reset if the static one is not equal to A
? Do I have to manually hide it using some artifice such as Dean Attali's shinyjs
?
Upvotes: 3
Views: 5372
Reputation: 988
Try this one. It's a combination of using reactive values and an observe.
require(shiny)
ui <- fluidPage(
# The static input
selectInput(inputId = 'static',
label = 'Make a choice',
choices = c('A', 'B', 'C'),
selectize = FALSE),
# The dynamic input
uiOutput(outputId = 'dynamicInput'),
# The output
hr(),
strong('This is a check for the output:'),
textOutput(outputId = 'check')
)
server <- function(input, output, session) {
## list to store reactive values
values <- reactiveValues()
# The dynamic input definition
output$dynamicInput <- renderUI({
# This input exists if the `static`
# one is equal to `A` only
if (input$static == 'A') {
selectInput(inputId = 'dynamic',
label = 'Choose a subset for `A`',
choices = c('A1', 'A2', 'A3'),
selectize = FALSE)
} else {
return(NULL)
}
})
## this bit fixes the issue
observe({
if (input$static == "A") {
values$dyn <- input$dynamic
} else {
values$dyn <- NULL
}
})
# The example output
output$check <- renderText({
paste(input$static, values$dyn)
})
}
shinyApp(ui, server)
Upvotes: 11