I have a two-step hierarchy of selectInputs. I want a solution that whenever I select a new "sports" the current values of the selectInput are reset to the default value 0. Right now my code only reset the values of the newly selected chosen sport. Not the old values of the previous "sport" of choice, I want both to be reset if possible. I thought if I chose all inputs to be updated in observeEvent it would fix that. But it appears it doesn't. Also I don't mind that if a sport has not been chosen that the input value is empty.
I have tried to look for other answers like this one: Shiny R: Reset other input values when selectInput value changes . But I am not sure this is the solution I want. Here is an example I wrote that explains it.
library(shiny)
# Define UI ----
ui <- fluidPage(
titlePanel("Menu"),
sidebarLayout(
sidebarPanel(
helpText("Chose Sport"),
selectInput("case",
label = "Sport",
choices = list(
"Hockey",
"Football",
"Basketball"
)),
uiOutput("mychoices")
),
mainPanel(
htmlOutput("printvalues")
)
)
)
# Define server logic ----
server <- function(input, output, session) {
gender <- selectInput( inputId="select_gender",
label = "Gender",
choices = list("Male" = 1, "Female" = 2, "-" = 0), selected = 0)
hockey <- selectInput( inputId="select_hockey",
label = "Hockey",
choices = list("A" = 1,
"B" = 2,
"C" = 3,
"-" = 0), selected = 0)
football <- selectInput( inputId="select_football",
label = "Football",
choices = list("D" = 1,
"E" = 2,
"F" = 3,
"G" = 5,
"-" = 0), selected = 0)
basketball <- selectInput( inputId="select_basketball",
label = "Basketball",
choices = list("H" = 1,
"I" = 2,
"-" = 0), selected = 0)
output$mychoices <- renderUI({
switch(input$case,
"Hockey" = list(gender, hockey),
"Football" = list(gender, football),
"Basketball" = list(gender, basketball),
)
})
observeEvent(input$case, {
# Reset all the input values to their default values
updateSelectInput(session, "select_gender", selected = 0)
updateSelectInput(session, "select_hockey", selected = 0)
updateSelectInput(session, "select_football", selected = 0)
updateSelectInput(session, "select_basketball", selected = 0)
})
output$printvalues = renderUI({
print_values <- c(input$select_gender, input$select_hockey, input$select_football, input$select_basketball)
print(print_values)
row.1 = paste("Gender:", input$select_gender)
row.2 = paste("Hockey:", input$select_hockey)
row.3 = paste("Football:", input$select_football)
row.4 = paste("Basketball:", input$select_basketball)
HTML(paste(row.1, row.2, row.3, row.4,sep="<br>"))
})
}
# Run the app ----
shinyApp(ui = ui, server = server)
Here is one way to do it using
shinyjs
package.