I want to print a tagList() with a textInput and a textAreaInput in a ModalDialog.
Then in this ModalDialog, I want to append a new element with a textInput and a textAreaInput by clicking a " " icon, increasing the ID number to 1.
The first element (with ID 0) is well created with tagAppendChild when the ModalDialog appears but clicking the " " icon doesn't add a second element using the observeEvent and tagAppendChild on my defined tagList.
Here is a reproducible Shiny code.
Any clue ? Thanx
ui <- fluidPage(
actionButton("open", "Modal")
)
server <- function(input, output, session) {
count <- reactiveVal(0)
my_list <- tagList()
observeEvent(input$open, {
count(0)
showModal(modalDialog(
tagAppendChild(my_list, add_item(count())),
actionButton(inputId = "add_entry", style = "border: 0px", label = NULL, icon("circle-plus")),
footer = tagList(modalButton("Cancel"), actionButton("Ok", "OK"))
))
})
add_item <- function(count) {
return(
tagList(
textInput(width=164, paste0("add_id",count), paste("ID", count()), placeholder="Only numbers allowed"),
textAreaInput(width=400, height=100, paste0("add_comment",count), "Comments")
)
)
}
observeEvent(input$add_entry, {
count(count() 1)
tagAppendChild(my_list, add_item(count()))
})
}
shinyApp(ui, server)
CodePudding user response:
We can use shiny::insertUI
to do this. Here I create a div inside the Modal with the id "modal_ui" that we'll use later to tell insertUI where I want to insert the ui.
observeEvent(input$add_entry, {
count(count() 1)
insertUI(selector = "#modal_ui", ui = add_item(count()))
})
App:
library(shiny)
ui <- fluidPage(
actionButton("open", "Modal")
)
server <- function(input, output, session) {
count <- reactiveVal(0)
my_list <- tagList()
observeEvent(input$open, {
count(0)
showModal(
modalDialog(
div(
id = "modal_ui",
add_item(count())
),
actionButton(
inputId = "add_entry",
style = "border: 0px",
label = NULL,
icon("circle-plus")
),
footer = tagList(modalButton("Cancel"), actionButton("Ok", "OK"))
)
)
})
add_item <- function(count) {
div(
id = paste0("div_", count),
textInput(
inputId = paste0("add_id", count),
label = paste("ID", count()),
width = 164,
placeholder = "Only numbers allowed"
),
textAreaInput(width = 400, height = 100, paste0("add_comment", count), "Comments")
)
}
observeEvent(input$add_entry, {
count(count() 1)
insertUI(selector = "#modal_ui", ui = add_item(count()))
})
}
shinyApp(ui, server)