R Shiny - Removing UI using jQuery and onclick event handler

Refresh

2 weeks ago

Views

18 time

0

The app below contains an actionButton Add box that creates a box when clicked. Each box has a AdminLTE data-widget = "remove" attribute, so each box has a remove button that is placed in the box-tools div in the box-header.

At the moment, clicking the remove button for a box only hides the box rather than removing it from the DOM. I have tried the jQuery function below:

$('[data-widget = \"remove\"]').click(function() {
                function removeBox (obj) {
                $(obj).closest('.newbox').remove();

                })

..which is called from the onclick handler that I have placed in the remove button tag (see server.R) but this doesn't seem to work.

Here is the reproducible code:

ui.R:

require(shinydashboard)
require(shinyjs)


# HEADER
header <- dashboardHeader()

# SIDEBAR
sidebar <- dashboardSidebar(

  tags$head(
    tags$script("

                $('[data-widget = \"remove\"]').click(function() {
                function removeBox (obj) {
                $(obj).closest('.newbox').remove();

                })


                ")
    ))

# BODY
body <- dashboardBody(shinyjs::useShinyjs(),

                      box(title = "Months", status = "primary", width = 12, solidHeader = T, background = "navy",
                          tags$div(id = 'add'),
                          tags$div(class = "pull-right",
                                   actionButton("addbox", "Add box")
                                   )
                          )
                      )


ui = dashboardPage(header, sidebar, body, shinyFeedback::useShinyFeedback())

server.R

server = function(input, output, session) {


  observeEvent(input$addbox, {
    id = paste0('box', input$addbox)
    insertUI(
      selector = '#add',
      ui = tags$div(class = "newbox",
                    id = id,
                    box(width = 12,
                        solidHeader = T,
                        title = div(h4(class = "box-title", paste("Month", input$addbox),
                                    div(class = "box-tools",
                                        tags$button(class = "btn btn-box-tool",
                                                    onclick = "removeBox(this)",
                                                    `data-widget` = "remove",
                                                    shiny::icon("remove")
                                                    )
                                        )
                                    ),

                                    selectizeInput(id, "Month name:", choices = month.name)

                                    )

                        ) #end tags$div
                    )
      )
    }) #end observeEvent


  } #end server

Where am I going wrong? I think I may have used an incorrect selector ('[data-widget = \"remove\"]') but I have tried .btn.btn-box-tool to no avail. Any help would be greatly appreciated.

1 answers

0

Вы добавляете обработчик событий OnClick с onclickатрибутом кнопки. Так что вам не нужно , чтобы добавить еще один. Просто используйте этот сценарий:

  tags$head(
    tags$script("
function removeBox(obj) {
  $(obj).closest('.newbox').remove();
}")
    )
  )

И это все. Нет необходимости устанавливать data-widgetатрибут.

Сценарий вы хотите использовать это странно:

$('[data-widget = \"remove\"]').click(function() {
  function removeBox (obj) { ......

Структура

$('[data-widget = \"remove\"]').click(function() {
 ***action to perform when the user clicks***
})

В вашем сценарии, вы определяете функцию, как «действия, чтобы выполнить», это не выполняет ничего.