'Limit row selection in DT Table in Shiny

I am currently trying to limit my selection in a DataTable in Shiny to just two rows - I want the table to not allow the user to click on more than rows (but also to have the ability to deselect them afterwards).

library(DT)
shinyApp(
  ui = fluidPage(
    fluidRow(
      column(12,
             dataTableOutput('table')
      )
    )
  ),
  server = function(input, output) {
    output$table <- DT::renderDataTable(iris, 
                                    options = list(selection = "multiple")
    )
  }
)

The row selection is currently on multiple mode, which works, but I don't want the selection to exceed two rows.



Solution 1:[1]

Update: Does not seem to work anymore, since 04.2022 or earlier.

You could either solve it via javascript, which you may have seen already: Limit row selection to 3 in datatables

Or you update the datatable in Shiny:

library(DT)
library(shiny)
shinyApp(
  ui = fluidPage(
    fluidRow(
      column(12,dataTableOutput('tbl'))
    )
  ),
  server = function(input, output) {
    reset <- reactiveValues(sel = "")
    output$tbl <- DT::renderDataTable({
      input$tbl_rows_selected
      datatable(iris, selection = list(mode = 'multiple', selected = reset$sel))
    })
    
    observe({
      if(length(input$tbl_rows_selected) > 2){
        reset$sel <- setdiff(input$tbl_rows_selected, input$tbl_row_last_clicked)
      }else{
        reset$sel <- input$tbl_rows_selected
      }
    })
  }
)

This solution might be less clean, but a bit easier to understand.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1