Delete the row in DT table shiny

Viewed 27

I am trying to delete the row in the table below but not able to . Can anyone please guide me here. The row should get deleted when the user selects the row and then clicks on action button

library(shiny)
library(httr)
library(jsonlite)
library(readxl)
library(DT)
library(glue)




ui <- fluidPage({
  au <- read_excel("au.xlsx")
  au <- as.data.frame(au)
  
  df <- reactiveValues(asd = NULL)
  mainPanel(
    
    
    dataTableOutput("ir"),
    actionButton("ac", "ac")
  )
  
  

})

server <- function(input, output, session) {
  
    output$ir <- renderDataTable({
      df$asd <- head(iris)
      datatable(df$asd)
    })
    
    observeEvent(input$ac,{
      # browser()
      df$asd <- df$asd[-c(as.numeric(input$ir_rows_selected)),]
      
    })
    
    

    }

shinyApp(ui, server)
1 Answers

Here is the way using a Shiny button:

library(shiny)
library(DT)

ui <- fluidPage(
  actionButton("delete", "Delete selected row"),
  br(),
  DTOutput("tbl")
)

server <- function(input, output, session){
  output[["tbl"]] <- renderDT({
    datatable(iris[1:5,],
              callback = JS(c(
                "$('#delete').on('click', function(){",
                "  table.rows('.selected').remove().draw();",
                "});"
              ))
    )    
  }, server = FALSE)
}

shinyApp(ui, server)

And here is the way using a button integrated in the DT table:

library(shiny)
library(DT)

ui <- fluidPage(
  br(),
  DTOutput("tbl")
)

server <- function(input, output, session){
  output[["tbl"]] <- renderDT({
    datatable(iris[1:5,],
              extensions = 'Buttons',
              options = list(
                dom = 'Bfrtip',
                buttons = list(
                  list(
                    extend = "collection",
                    text = "Delete selected row",
                    action = DT::JS(c(
                      "function ( e, dt, node, config ) {",
                      "  dt.rows('.selected').remove().draw();",
                      "}"))
                  )
                )
              )
    )
  }, server = FALSE)
}

shinyApp(ui, server)

enter image description here

With these methods, the table is not re-rendered when the row is deleted.

Related