Skip to content Skip to sidebar Skip to footer

Delete Datatable Rows In Shiny App Using Javascript

I'm trying to remove rows from a Datatable in a Shiny app using Javascript. In the table I have a column with a 'delete' button for each row. This would be more or less what I'm tr

Solution 1:

library(DT)
library(shiny)

rowNames = FALSE # whether to show row names
colIndex <- as.integer(rowNames)

dat = iris[1:5,]

dat[["Action"]] <- vapply(seq_len(nrow(dat)), function(i){
  as.character(tags$button("delete", id = paste0("delete-",i), `data-index` = i))
}, FUN.VALUE = character(1L))
dat[["rowId"]] <- paste0("row-", seq_len(nrow(dat)))

callback <- JS(
  '$("button[id^=delete]").on("click", function() {',
  '  var index = $(this).data("index");',
  '  var rowId = "#row-" + index;',
  '  table.row(rowId).remove().draw();',
  '});'
)

datatable(
  dat,
  rownames = rowNames,
  escape = -ncol(dat)+1L,
  callback = callback,
  options = list(
    rowId = JS(sprintf("function(data){return data[%d];}",
                       ncol(dat)-1L+colIndex)),
    columnDefs = list(
      list(visible = FALSE, targets = ncol(dat)-1L+colIndex),
      list(className = "dt-center", targets = "_all")
    )
  )
)

Post a Comment for "Delete Datatable Rows In Shiny App Using Javascript"