Home > Blockchain >  DT does not allow selecting the maximum number of lines
DT does not allow selecting the maximum number of lines

Time:07-29

I tried to select a maximum number of rows in a DT through a jQuery function. But, it doesn't work. I think I'm using it incorrectly. I put the corresponding id (row_modif) in the function, but even then it doesn't select 5 lines at most.

My code:

library(shiny)
library(DT)

ui <- basicPage(
  
  mainPanel(
    HTML(
      "<script>
      
$(document).ready(function() {    
$('#row_modif').dataTable( {
        'bPaginate': true,
        'bLengthChange': false,
        'bFilter': true,
        'bSort': true,
        'bInfo': true,
        'bAutoWidth': false
    } );
    /* Add/remove class to a row when clicked on */
    $('#row_modif tr').click( function() {
        if($('.row_selected').length < 6 || 
           $(this).hasClass('row_selected')) {
            $(this).toggleClass('row_selected');
        }
    } );
 } );
 $('#row_modif').css('min-height','300');  

$('.btn_r').click(function(){
  $('.row_selected').removeClass('row_selected')
});
    </script>"
    ),
    DT::dataTableOutput('row_modif'),
    tags$p("Selected Row:\n"),
    textOutput("selectedrow"), 
    tags$p("Species and Sepal Length for Selected Row:\n"), 
    DT::dataTableOutput("sscols")
  ))

server <- function(input, output, session) {
  
  output$row_modif <- DT::renderDataTable({
    
    DT::datatable(data = iris)
      
  })
    
    output$selectedrow <- renderPrint({sort(x = input$row_modif_rows_selected)})
    
    output$sscols <- DT::renderDataTable({
      
      datatable(
        data = iris[sort(input$row_modif_rows_selected), c("Species", "Sepal.Length")],
        options = list(
          pageLength = 8,
          buttons = list(list(
              extend = "csv",
              filename = "Consulta",
              fieldSeparator = ";"
            )), dom = 'Blfrtip'), extensions = 'Buttons'
      )
      
    })
  
}
  
shinyApp(ui, server)

How to adjust this function so that the DT allows selecting only 5 lines at most?

CodePudding user response:

With the Select extension:

library(shiny)
library(DT)

callback <- JS(
  "table.on( 'select', function ( e, dt, type, ix ) {",
  "  var selected = dt.rows({selected: true});",
  "  if ( selected.count() > 5 ) {",
  "    dt.rows(ix).deselect();",
  "  }",
  "})"
)

ui <- fluidPage(
  br(),
  DTOutput("dtable")
)

server <- function(input, output) {
  output$dtable <- renderDT({
    datatable(
      iris,
      extensions = "Select",
      selection = "none",
      callback = callback,
      options = list(
        select = "multi"
      )
    )
  }, server = FALSE)
}

shinyApp(ui, server)

enter image description here

  • Related