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

佐手、 提交于 2019-12-01 20:14:45

问题


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 button all the fields become empty, It's like if I must define how many fields I want in advance. Any help will be very appreciated.

Thank you

Here is my code:

library(shiny)

shiny::runApp(list(
ui = pageWithSidebar(
headerPanel("test"),
sidebarPanel(
  helpText("Alternatives list"),
  verbatimTextOutput("summary")
),    
mainPanel(  
  actionButton("obs","add"),
  htmlOutput("selectInputs")     
)  
)
, 

server = function(input,output){
observe({

  if (input$obs == 0) 
    return()
  isolate({

    output$selectInputs <- renderUI({
      if(!is.null(input$obs))  
        print("w")
      w <- ""
      for(i in 1:input$obs) {
        w <- paste(w,textInput(paste("a",i,sep=""),paste("a",i,sep="")))
      }
      HTML(w)
    })
    output$summary <- renderPrint({  
      print("your Alternative are:")

      for(i in 1:input$obs) {
        print(              
          input[[sprintf("a%d",i)]]
        )
      }
    })
    outputOptions(output, 'selectInputs', suspendWhenHidden=FALSE)
  })
})
}))

回答1:


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)
    })


来源:https://stackoverflow.com/questions/22160372/r-shiny-how-to-build-dynamic-ui-text-input

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!