jeudi 25 mai 2023

Add multiple checkboxes in shiny datatable and retrieve it's value

I added multiple checkbox columns (check1, check2) to the datatable. I have corresponding table with bool1 and bool2 that I want to update based on the reactives for the checkboxes. I am able to retrieve the data for check1 only. I need to update the callback function to take in both check1 and check2 columns but I am not too familiar with JS. Need help figuring this out.

library(shiny)
library(DT)

ui <- fluidPage(
  br(),
  fluidRow(
    column(
      6,
      DTOutput("dtable")
    ),
    column(
      6,
      verbatimTextOutput("reactiveDF")
    )
  )
)

shinyInput <- function(FUN, len, id, ...) {
  inputs <- character(len)
  for (i in seq_len(len)) {
    inputs[i] <- as.character(FUN(paste0(id, i), label = NULL, ...))
  }
  inputs
}

dat0 <- data.frame(
  fruit  = c("apple", "cherry", "pineapple", "pear"),
  letter = c("a", "b", "c", "d")
)

dat1 <- cbind(dat0, bool1 = FALSE, bool2 = FALSE)

dat2 <- cbind(
  dat0,
  check1 = shinyInput(checkboxInput, nrow(dat0), "checkb"),
  check2 = shinyInput(checkboxInput, nrow(dat0), "checkc")
)

js <- c(
  "$('[id^=checkb]').on('click', function(){",
  "  var id = this.getAttribute('id');",
  "  var i = parseInt(/checkb(\\d+)/.exec(id)[1]);",
  "  var value = $(this).prop('checked');",
  "  var info = [{row: i, col: 3, value: value}];",
  "  Shiny.setInputValue('dtable_cell_edit:DT.cellInfo', info);",
  "})"
)

server <- function(input, output, session) {

  Dat <- reactiveVal(dat1)

  output[["dtable"]] <- renderDT({
    datatable(
      dat2,
      rownames = TRUE,
      escape = FALSE,
      editable = list(target = "cell", disable = list(columns = c(3,4))),
      selection = "none",
      callback = JS(js)
    )
  }, server = FALSE)

  observeEvent(input[["dtable_cell_edit"]], {
    info <- input[["dtable_cell_edit"]] # this input contains the info of the edit
    print(info)
    Dat(editData(Dat(), info))
  })

  output[["reactiveDF"]] <- renderPrint({
    Dat()
  })

}

shinyApp(ui, server)



Aucun commentaire:

Enregistrer un commentaire