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