简体   繁体   中英

How to update numericInput default value based on DT row selected

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM