Reputation: 89
I have created a table which looks as per screenshot. How could I add an excel like filter button where I could select multiple specific items of the list?
And code is the following:
DT::datatable(current_list,
rownames = FALSE,
filter = 'top',
options = list(pageLength = 50,lengthChange = FALSE,autoWidth = FALSE,escape=FALSE, searching = TRUE,
columnDefs = list(list(className = 'dt-center', targets = 0:1),
list(width = '30px', targets = 0:0),
list(width = '270px', targets = 1:1)
)
)
)
Upvotes: 1
Views: 1573
Reputation: 84709
library(DT)
dat <- iris
sketch <- htmltools::tags$table(
tableHeader(c("",names(dat))),
tableFooter(rep("", 1+ncol(dat)))
)
js <- c(
"function(){",
" this.api().columns().every(function(){",
" var column = this;",
" var select = $('<select multiple=\"multiple\"><option value=\"\"></option></select>')",
" .appendTo( $(column.footer()).empty() )",
" .on('change', function(){",
" var vals = $('option:selected', this).map(function(index,element){",
" return $.fn.dataTable.util.escapeRegex($(element).val());",
" }).toArray().join('|');",
" column.search(vals.length > 0 ? '^('+vals+')$' : '', true, false).draw();",
" });",
" column.data().unique().sort().each(function(d,j){",
" select.append('<option value=\"'+d+'\">'+d+'</option>')",
" });",
" });",
"}")
datatable(dat, container=sketch,
options = list(
initComplete = JS(js)
)
)
The row names are character strings and then they are sorted like this: 1, 10, 100, .... Not nice. With the following code, they are not sorted and this is better:
js <- c(
"function(){",
" this.api().columns().every(function(i){",
" var column = this;",
" var select = $('<select multiple=\"multiple\"><option value=\"\"></option></select>')",
" .appendTo( $(column.footer()).empty() )",
" .on('change', function(){",
" var vals = $('option:selected', this).map(function(index,element){",
" return $.fn.dataTable.util.escapeRegex($(element).val());",
" }).toArray().join('|');",
" column.search(vals.length > 0 ? '^('+vals+')$' : '', true, false).draw();",
" });",
" var data = column.data();",
" if(i == 0){",
" data.each(function(d,j){",
" select.append('<option value=\"'+d+'\">'+d+'</option>');",
" });",
" }else{",
" data.unique().sort().each(function(d,j){",
" select.append('<option value=\"'+d+'\">'+d+'</option>');",
" });",
" }",
" });",
"}")
Upvotes: 1