Adapt/update filter choices to already applied filters in shiny DT datatable

I am using the package DT to display a table in r shiny. When I apply a filter in one column the filter choices of the other columns don´t adapt to the already filtered table. So in the example below if you filter sepal.length with 4.3 ... 4.8 you still get the option to filter species "virginica" even when there is no entry that has sepal.length between 4.3 and 4.8 and is "virginica". This is especially troublesome when you want to filter factor columns with more than 100 levels.

To this problem there is already a solution written in JavaScript. See this link: Update select filters — DataTables forums and a live demo of the solution: JS Bin - Collaborative JavaScript Debugging However I don´t know how to implement this in shiny.

Here is a small example with the Iris dataset.
'''

library(shiny)
library(DT)

ui <- fluidPage(
  fluidRow(column(12, DTOutput("table"))
  )
)

server <- function(input, output, session) {
  output$table <- renderDT({

    DT::datatable(iris, filter = "top")
  })
}

shinyApp(ui, server)

How do I adapt the JavaScript Code to get this function working in Shiny and where do I insert the code snippet.

# function of the live demo in the link above

$(document).ready(function() {
  var table = $('#example').DataTable( {
    initComplete: function () {
      this.api().columns().every( function () {
        var column = this;
        var select = $('<select><option value=""></option></select>')
          .appendTo( $(column.footer()).empty() )
          .on( 'change', function () {
            var val = $.fn.dataTable.util.escapeRegex(
              $(this).val()
            );

            column
              .search( val ? '^'+val+'$' : '', true, false )
              .draw();
          } );

        column.data().unique().sort().each( function ( d, j ) {
          select.append( '<option value="'+d+'">'+d+'</option>' );
        } );
      } );
    }
  } );

  table.on('draw', function () {
    table.columns().indexes().each( function ( idx ) {
      var select = $(table.column( idx ).footer()).find('select');

      if ( select.val() === '' ) {
        select
          .empty()
          .append('<option value=""/>');

        table.column(idx, {search:'applied'}).data().unique().sort().each( function ( d, j ) {
          select.append( '<option value="'+d+'">'+d+'</option>' );
        } );
      }
    } );
  } );
} );

This topic was automatically closed 54 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.