I am trying to create a shiny application which will enable users to add text boxes, or add images and create a document from it. I am able to add one Textbox and display its contents but when I add another textbox, the contents are not displayed. I have used a link as a starting point.
Here is my sample code that I am trying to add more user input text boxes by clicking add button.
library(shiny)
library(shinyjqui)
ui <- shinyUI(fluidPage(
sidebarPanel(
actionButton("add_btn", "Add Textbox"),
actionButton("rm_btn", "Remove Textbox"),
textOutput("counter")
),
mainPanel(
jqui_sortable(
div(id = 'textboxes',
uiOutput("textbox_ui"),
textInput("caption", "Caption", "Insert Text"),
verbatimTextOutput("value")
)
)
)
))
server <- shinyServer(function(input, output, session) {
# Track the number of input boxes to render
counter <- reactiveValues(n = 0)
#Track the number of input boxes previously
prevcount <- reactiveValues(n = 0)
observeEvent(input$add_btn, {
counter$n <- counter$n + 1
prevcount$n <- counter$n - 1})
observeEvent(input$rm_btn, {
if (counter$n > 0) {
counter$n <- counter$n - 1
prevcount$n <- counter$n + 1
}
})
output$value <- renderText({ input$caption })
output$counter <- renderPrint(print(counter$n))
textboxes <- reactive({
n <- counter$n
if (n > 0) {
# If the no. of textboxes previously where more than zero, then
#save the text inputs in those text boxes
if(prevcount$n > 0){
vals = c()
if(prevcount$n > n){
lesscnt <- n
isInc <- FALSE
}else{
lesscnt <- prevcount$n
isInc <- TRUE
}
for(i in 1:lesscnt){
inpid = paste0("textin",i)
vals[i] = input[[inpid]]
}
if(isInc){
vals <- c(vals, "Insert Text")
}
lapply(seq_len(n), function(i) {
textInput(inputId = paste0("textin", i),
label = paste0("Subsection ", i), value = vals[i])
})
}else{
lapply(seq_len(n), function(i) {
textInput(inputId = paste0("textin", i),
label = paste0("Subsection ", i), value = "Insert text")
})
}
}
})
output$textbox_ui <- renderUI({ textboxes() })
})
shinyApp(ui, server)
Any help will be appreciated in this regard. If anyone can point me in how to dynamically capture output$value everytime a new box is added it would push me in the right direction.