Home > Mobile >  How to perform literal search in Shiny DataTable column filter?
How to perform literal search in Shiny DataTable column filter?

Time:09-18

This one has stumped me, and although I've looked into DataTables specific solutions (enter image description here

Note: usage in Shiny

In order to use the search builder in a Shiny app, you have to set the option server = FALSE in the renderDT function. Server-side searching is not supported.


EDIT

Here is a way without the search builder. It has an inconvenient: you have to specify the index of the column in which you want to search. That's because DataTables supports exact regex search only on a column basis.

library(DT)

dat <- data.frame(
  car = c("Mazda", "Mazda RX4", "Mazda RX4 Wag", "Ford", "Mercedes"),
  day = Sys.Date()   0:4
)

js <- c(
  "function(settings){",
  "  var instance = settings.oInstance;",
  "  var table = instance.api();",
  "  var input = instance.parent().find('.dataTables_filter input');",
  "  input.off('keyup search input').on('keyup', function(){",
  "    var keyword = '^'   input.val()   '$';",
  "    // we search in column 1",
  "    table.column(1).search(keyword, true, false).draw();",
  "  });",
  "}"
)

datatable(
  dat,
  options = list(initComplete = JS(js))
)

EDIT

Finally, here is how to search an exact match in the column-wise filter boxes:

library(DT)

dat <- data.frame(
  car = c("Mazda", "Mazda RX4", "Mazda RX4 Wag", "Ford", "Mercedes"),
  pet = c("dog", "dog", "cat", "cat", "cat"),
  day = Sys.Date()   0:4
)

js <- c(
  "function(settings){",
  "  var instance = settings.oInstance;",
  "  var table = instance.api();",
  "  var $inputs = instance.parent().find('.form-group input');",
  "  $inputs.off('keyup search input').on('keyup', function(){",
  "    var keyword = '^'   $(this).val()   '$';",
  "    var index = 1   $inputs.index(this);", # add 1 for the rownames column
  "    table.column(index).search(keyword, true, false).draw();",
  "  });",
  "}"
)

datatable(
  dat, filter = "top", 
  options = list(initComplete = JS(js))
)

enter image description here

  • Related