I'd like to update the numericInput value based on the different row users select from a DT table.
Below is my simple example. So, if users select the 1st row, the value should be 50. If users select the 2nd row, the value should be 100. Is there a way to do it without using the 'refresh' button?
library(shiny)
library(DT)
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
numericInput("price",
"Average price:",
min = 0,
max = 50,
value = 0),
actionButton('btn', "Refresh")
),
mainPanel(
DT::dataTableOutput('out.tbl')
)
)
)
server <- function(input, output, session) {
price_selected <- reactive({
if (input$out.tbl_rows_selected == 1) {
price = 50
} else {
price = 100
}
})
observeEvent (input$btn, {
shiny::updateNumericInput(session, "price", value = price_selected())
})
output$out.tbl <- renderDataTable({
Level1 <- c("Branded", "Non-branded")
Level2 <- c("A", "B")
df <- data.frame(Level1, Level2)
})
}
shinyApp(ui = ui, server = server)
Solution using your reactive variable
price_selected <- reactive({
if (isTRUE(input$out.tbl_rows_selected == 1)) {
price = 50
} else {
price = 100
}
})
shiny::observe({
shiny::updateNumericInput(session, "price", value = price_selected())
})
Note that you can observe input$out.tbl_rows_selected
directly (you don't need the reactive variable)