0

I have a app that I am testing from a previous example: How to add/remove input fields dynamically by a button in shiny

My question is, where are textInput values saved? and how can I display them as verbatimTextOutput in the mainPanel.

I tried creating a renderText with input$textin, but it did not work

Here's the code:

library(shiny)

ui <- shinyUI(fluidPage(
  
  sidebarPanel(
    
    actionButton("add_btn", "Add Textbox"),
    actionButton("rm_btn", "Remove Textbox"),
    textOutput("counter")
    
  ),
  
  mainPanel(
    uiOutput("textbox_ui"),
  verbatimTextOutput("textout")
  )
  
))

server <- shinyServer(function(input, output, session) {
  
  # Track the number of input boxes to render
  counter <- reactiveValues(n = 0)
  
  # Track all user inputs
  AllInputs <- reactive({
    x <- reactiveValuesToList(input)
  })
  
  observeEvent(input$add_btn, {counter$n <- counter$n + 1})
  observeEvent(input$rm_btn, {
    if (counter$n > 0) counter$n <- counter$n - 1
  })
  
  output$counter <- renderPrint(print(counter$n))
  
  textboxes <- reactive({
    
    n <- counter$n
    
    if (n > 0) {
      isolate({
        lapply(seq_len(n), function(i) {
          textInput(inputId = paste0("textin", i),
                    label = paste0("Textbox", i), 
                    value = AllInputs()[[paste0("textin", i)]])
        })
      })
    }
    
  })
  
  output$textbox_ui <- renderUI({ textboxes() })
  
  output$textout <- renderText({ input$textin })
  
})

shinyApp(ui, server)
writer_typer
  • 708
  • 7
  • 25

1 Answers1

1

The Id of the textInput is created by inputId = paste0("textin", i), ie :

  • input$textin1
  • input$textin2
  • ...

You can output for example the first one by using :

output$textout <- renderText({ input$textin1 })

You could also create a loop to output all the newly created inputs :

  output$textout <- renderText({ 
    n <- counter$n
    paste(lapply(1:n,function(n) {input[[paste0('textin',n)]]}),collapse=' ')
    })

enter image description here

Waldi
  • 39,242
  • 6
  • 30
  • 78
  • This is helpful. How do I have a textoutput that has all the input from all the textboxes? For example, I write "Hello" in Textbox1, then I click Add Textbox, and write "World" in Textbox2. I would like the textoutput to say Hello (next line) World. – writer_typer Jul 10 '20 at 22:24
  • One last thing, how do I make them appear in new lines? – writer_typer Jul 10 '20 at 22:52
  • 1
    You can use '\n' instead of ' ' for collapse – Waldi Jul 11 '20 at 05:17