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

标签 r textinput shiny

我正在尝试使用 R Shiny 构建动态textInput。用户应该在文本字段中写入,然后按添加按钮来填充另一个字段。但是,每次我按下按钮时,所有字段都会变空,就像我必须提前定义我想要多少个字段一样。任何帮助将不胜感激。

谢谢

这是我的代码:

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

最佳答案

您的问题是每次单击按钮时都会重新生成所有按钮(因此输入$aX)。而且它们默认生成时没有值,这就是为什么当你读取它们时它们都是空的。

例如,如果您抑制 output$selectInputs 代码中的循环,您就会看到错误:(但现在它只允许您设置每个 aX 一次。)

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

保留您的代码(然后保留所有按钮的重新生成),您应该向每个 textInput 的 value 参数添加他的“自己的值”(实际上,具有相同 id 的旧输入的值)值=输入[[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)
    })

关于R Shiny : How to build dynamic UI (text input),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22160372/

相关文章:

r - 如何在 Neo4j 中使用 Cypher 查询进行 group_by 和计算百分比

jquery - 使用文本框的属性之一设置文本框的值 (jQuery)

我自己网站上的 R Shiny 应用

r - 使用列名称字符串在箭头中收集之前进行汇总

r - 在 coord_polar 上制作弯曲文本

r - 在 ubuntu 界面上的 R 中安装 e1071

使用媒体查询时 Android 键盘无法打开

Java:使用命令行参数处理文件名

r - 在 R/Shiny 中,htmlOutput()/renderUI() 的最佳替代方案?

javascript - rhandsontable 如何限制最大。行数