Limit row selection in DT Table in Shiny

血红的双手。 提交于 2020-08-08 03:45:51

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/43805799/limit-row-selection-in-dt-table-in-shiny

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!