Quantcast
Channel: Generate observers for dynamic number of inputs - Stack Overflow
Viewing all articles
Browse latest Browse all 2

Generate observers for dynamic number of inputs

$
0
0

I have what I think is a pretty simple user case that I haven't been able to find a solution for: I want Shiny to generate a user-specified number of inputs, dynamically creating an observer for each.

In the minimal reproducible code below, the user indicates the number of action buttons desired by typing into the textInput widget; he or she then presses "submit", which generates the action buttons.

What I want is for the user to then be able to click on any action button and generate an output specific to it (e.g. for the minimal case, just print the name of the button):

library("shiny")ui <- fluidPage(textInput("numButtons", "Number of buttons to generate"),                 actionButton("go", "Submit"), uiOutput("ui"))server <- function(input, output) {        makeObservers <- reactive({                lapply(1:(as.numeric(input$numButtons)), function (x) {                        observeEvent(input[[paste0("add_", x)]], {                                print(paste0("add_", x))                        })                })         })        observeEvent(input$go, {                output$ui <- renderUI({                        num <- as.numeric(isolate(input$numButtons))                        rows <- lapply(1:num, function (x) {                                actionButton(inputId = paste0("add_", x),                                          label = paste0("add_", x))                        })                        do.call(fluidRow, rows)                })                makeObservers()        })}shinyApp(ui, server)

The problem with the code above is that somehow several observers are created, but they all take as their input only the last item in the list passed to lapply. So if I generate four action buttons, and I click on action button #4, Shiny prints its name four times, while all the other buttons don't react.

The idea to generate observers using lapply comes from https://github.com/rstudio/shiny/issues/167#issuecomment-152598096


Viewing all articles
Browse latest Browse all 2

Latest Images

Trending Articles





Latest Images