Brilliant DataTable: disable row selection for specific rows

I am trying to determine if it is possible to shiny DataTabledisable row selection for specific rows.

Using the parameter selection DT::datatable, I can pre-select rows, determine whether the user selects rows or columns, or both, and completely disable the selection, but it is not clear to me whether I can specify specific rows to exclude. Is it possible?

Hello

+4
source share
1 answer

With the extension Selectyou can do:

library(DT)
library(shiny)

dat <- iris[1:17,]

rowCallback <- c(
  "function(row, data, displayNum, displayIndex){",
  "  var indices = [0, 2, 4, 15];",
  "  if(indices.indexOf(displayIndex) > -1){",
  "    $(row).find('td').addClass('notselectable');",
  "  }",
  "}"
)

shinyApp(
  ui = fluidPage(
    DTOutput("table")
  ),
  server = function(input, output, session) {    
    output[["table"]] <- renderDT({
      dat %>%
        datatable(options = list(
          rowCallback = JS(rowCallback), 
          select = list(style = "multi", selector = "td:not(.notselectable)")
        ), 
        extensions = "Select", selection = "none"
        )
    }, server = FALSE)
  }
)

But if you need the indices of the selected rows in input$table_rows_selected, you need input$table_rows_selectedJavaScript code for this:

callback <- c(
  "var id = $(table.table().node()).closest('.datatables').attr('id');",
  "table.on('click', 'tbody', function(){",
  "  setTimeout(function(){",
  "    var indexes = table.rows({selected:true}).indexes();",
  "    var indices = Array(indexes.length);",
  "    for(var i = 0; i < indices.length; ++i){",
  "      indices[i] = indexes[i];",
  "    }",
  "    Shiny.setInputValue(id + '_rows_selected', indices);",
  "  }, 0);",
  "});"
)

shinyApp(
  ui = fluidPage(
    DTOutput("table")
  ),
  server = function(input, output, session) {    
    output[["table"]] <- renderDT({
      dat %>%
        datatable(
          callback = JS(callback),
          options = list(
            rowCallback = JS(rowCallback), 
            select = list(style = "multi", selector = "td:not(.notselectable)")
          ), 
          extensions = "Select", selection = "none"
        )
    }, server = FALSE)
    observe({
      print(input[["table_rows_selected"]])
    })
  }
)
0

Source: https://habr.com/ru/post/1629444/


All Articles