0

I've been using shiny recently,

I want to create a dynamic textinput, but I'm still confused about how to access the value of the text input. I found this code from. Mikko Marttila

but the values that appear are still random and unordered >> [1] "3" "1" "0" "2" "3" I only need the values from textin without the value from add_btn & rm_btn which are sorted by textbox. Like this :

[1] "1" "2" "3"

enter image description here

Code:

#======================================================================================
library(shiny)

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

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$my_inputs <- renderPrint({
    paste0(AllInputs())
  })
  output$my_inputs2 <- renderPrint({
    paste0(str(AllInputs()))
  })
  
})

shinyApp(ui, server)

Thank you

1 Answers1

0

If you add this bit of code to your server section:

  observe({
    names_inputs <- names(AllInputs())[grepl("textin", names(AllInputs()))]
    
    AllInputs()[names(AllInputs()) %in% names_inputs] |> 
      unlist() |> 
      print()
  })

The text will print to your console.

Phil
  • 7,287
  • 3
  • 36
  • 66