Jitu Deka
Jitu Deka

Reputation: 75

Problem in inserting UI after removing the ui

I am trying to remove ui in shiny app. I have the code to remove each of the ui element separately with separate remove buttons. But additionally I would also like a generic delete button to remove all the inserted ui at once. For the task I tried the selector from insertUI and was able to delete all the added UIs.

But after this specific task i.e after removing all the UIs at once, shiny is not allowing me to insert any new UIs. It seems that the division ID has been removed permanently and couldn't be regenerated even after invoking the add button. How to solve this problem, please anyone guide me.

Below is the workable code and is adopted from stackoverflow

 library(shiny)

   ui <- fluidPage(


 sidebarLayout(
     sidebarPanel(

     actionButton('addBtn', 'Add input Set'),
     actionButton("remove","Delete"),


  tags$div(id='inputList')
),
mainPanel()
))

  server <- function(input, output) {

     observeEvent(input$addBtn, {

       # Increment by 1
       nr <- input$addBtn + 1

       # Creating a list of IDs based on our increments

       id <- paste0("input",nr)
       row_id <- paste0("newInput",nr)

       # Inserting the UIs

  insertUI(
       selector = '#inputList',
        ui=div(
         id = row_id,
         selectizeInput(
           inputId = id,
           choices = c("Stuff","to","input"),
           selected = c("Stuff"),
           label = "An Input:"          
      ),


    actionButton(paste0('removeBtn',nr), 'Remove')
    )
  )

  # Removes UI seperately 
  # Uses Seperate remove button for each ui

    observeEvent(input[[paste0('removeBtn',nr)]],{
      shiny::removeUI(
       selector = paste0("#newInput",nr)
    )
    })  

 })

 # Remove all the added UIs at once
 # InsertUI doesn't work after this


 observeEvent(input$remove,{

    removeUI(selector = "#inputList")


    })

 }

   shinyApp(ui, server)

Upvotes: 4

Views: 488

Answers (1)

St&#233;phane Laurent
St&#233;phane Laurent

Reputation: 84529

That's normal because your removeUI removes the div(id = "inputList"). So after that the insertUIs do not find this div.

Use instead:

removeUI(selector = "#inputList *", multiple = TRUE)

The CSS selector #inputList * selects all descendants of #inputList, but not #inputList.

Upvotes: 4

Related Questions