【问题标题】:R shiny: How to build dynamic UI (text input)R Shiny:如何构建动态 UI(文本输入)
【发布时间】:2014-04-05 07:18:25
【问题描述】:

我正在尝试使用 R 闪亮构建动态 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)
  })
})
}))

【问题讨论】:

    标签: r textinput shiny


    【解决方案1】:

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

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

        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 的旧输入的值)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)
        })
    

    【讨论】:

      猜你喜欢
      • 2020-10-14
      • 2014-07-04
      • 2019-02-05
      • 1970-01-01
      • 2018-11-28
      • 2023-04-01
      • 1970-01-01
      • 2019-06-14
      • 2017-01-30
      相关资源
      最近更新 更多