Yang-Tang/shinyjqui

order for jqui_sortable not returned when using insertUI

gacolitti opened this issue · 2 comments

Related to issue #43.

I want to insert an arbitrary number of ui elements inside a jqui_sortable(), and have the order of the elements available inside the server function.

Right now, if I know beforehand how many elements are needed I can call the jqui_sortable() function inside insertUI and then access the order of the elements in the server:

library(shiny)

ui <- fluidPage(
  actionButton("add", "Add"),
  div(id = "foo")
)

server <- function(input, output, session) {
  observeEvent(input$add, {
    insertUI(selector = "#foo",
             where = "beforeEnd",
             ui = jqui_sortable(tags$ul(
               id = paste0('lst', input$add),
               tags$li('A'),
               tags$li('B'),
               tags$li('C')
             )))
  })

  observe({
    cat(str(input$lst_order1))
    cat(str(input$lst_order2))
  })
}

shinyApp(ui, server)

If you run the above app, you will see the order of the first two lists that are inserted printed to the console. Changing the order of the elements also prints to the console.

However, if I try to put the jqui_sortable() in the UI and insert only the elements, the order is not printed. Here is a reproducible example:

library(shiny)
library(shinyjqui)

ui <- fluidPage(
  actionButton("add", "add"),
  jqui_sortable(tags$ul(id = "lst")),
)

server <- function(input, output, session) {
  
  observeEvent(input$add, {
    insertUI(
      selector = "#lst",
      where = "beforeEnd",
      ui = tags$li(paste0("test", input$add))
    )
  })
  
  observe({
    cat(str(input$lst_order))
  })
}

shinyApp(ui, server)

Is what I'm trying to do even possible?

Crossposted on stackoverflow: https://stackoverflow.com/questions/70425744/order-for-jqui-sortable-not-returned-when-using-insertui-in-shiny

Hi @gacolitti This is because the sortable was not informed when a new item was inserted by insertUI. Currently, I can't find any good solution because the insertUI function dosen't trigger any JS event. You have to first destroy the sortable then recreate it as what the stackoverflow's answer did.

@Yang-Tang Got it. Thanks for the help.