R shiny: How to build dynamic UI (text input)

后端 未结 1 1689
轮回少年
轮回少年 2021-01-19 00:58

I\'m trying to build dynamic textInput with R shiny. The user should write in a text field then push an add button to fill another field. However, each time I push the butto

1条回答
  •  执念已碎
    2021-01-19 01:14

    Your problem is that you regenerate all the buttons (so the input$aX) each time you click on the button. And they are generated without value by default, that's why when you read them they are all nulls.

    For example you can see your mistake if you supress the loop in your output$selectInputs code : (But now it only allow you to set each aX only 1 time.)

        output$selectInputs <- renderUI({
          if(!is.null(input$obs))
            print("w")
          w <- ""
          w <- paste(w, textInput(paste("a", input$obs, sep = ""), paste("a", input$obs, sep = "")))
          HTML(w)
        })
    

    Keeping your code (then keeping the regeneration of all the buttons), you should add to the value argument of each textInput his "own value" (in reality, the value of the old input with the same id) value = input[[sprintf("a%d",i)]] :

        output$selectInputs <- renderUI({
          w <- ""
          for(i in 1:input$obs) {
            w <- paste(w, textInput(paste("a", i, sep = ""), paste("a", i, sep = ""), value = input[[sprintf("a%d",i)]]))
          }
          HTML(w)
        })
    

    0 讨论(0)
提交回复
热议问题