Reputation: 1932
I have a shiny App where I am displaying the same output multiple times. I have two inputs and they need to both control the same output. In my example below the outputs are copies of each other and it has to stay that way. Currently only the first input does anything. I need them to control the same output and react to changes in each other.
ui <- function(request) {
fluidPage(
textInput("txt1", "Enter text1"),
textInput("txt1", "Enter text2"),
checkboxInput("caps", "Capitalize"),
verbatimTextOutput("out1"),
verbatimTextOutput("out2"),
)
}
server <- function(input, output, session) {
output$out2<- output$out1 <- renderText({
if (input$caps)
toupper(input$txt1)
else
input$txt1
})
}
shinyApp(ui, server, enableBookmarking = "url")
Upvotes: 0
Views: 1033
Reputation: 10152
I have had a similar situation where I needed multiple identical inputs (albeit I only needed one output) that always have the same value.
The solution for me was to create a reactive element that holds the value for the inputs and syncs the value with the inputs.
Ie this code always makes input 1 and 2 have the same values
library(shiny)
ui <- fluidPage(
selectInput("id1", "Input 1", choices = c("A", "B")),
selectInput("id2", "Input 2", choices = c("A", "B")),
)
server <- function(input, output, session) {
# the reactive value always holds the value from the inputs
input_filter <- reactiveVal("A")
# sync from the reactive value to the inputs
observeEvent(input_filter(), {
print("input_filter() has changed")
updateSelectInput(session, "id1", selected = input_filter())
updateSelectInput(session, "id2", selected = input_filter())
})
# sync from the inputs to the reactive value
observeEvent(input$id1, {
print("Update id1")
input_filter(input$id1)
})
observeEvent(input$id2, {
print("Update id2")
input_filter(input$id2)
})
}
shinyApp(ui, server)
Upvotes: 0
Reputation: 10365
You need to give your inputs unique IDs, but in your code both IDs are txt1
. If you change this, you can use the normal reactivity:
library(shiny)
ui <- function(request) {
fluidPage(
textInput("txt1", "Enter text1"),
textInput("txt2", "Enter text2"),
checkboxInput("caps", "Capitalize"),
verbatimTextOutput("out1"),
verbatimTextOutput("out2"),
)
}
server <- function(input, output, session) {
output$out2<- output$out1 <- renderText({
if (input$caps)
paste(toupper(input$txt1), toupper(input$txt2))
else
paste(input$txt1, input$txt2)
})
}
shinyApp(ui, server, enableBookmarking = "url")
Upvotes: 1