Enable smart search in shiny datatable columns

42 views Asked by At

I have implemented the following shiny table, where users can filter the whole table or specific columns. However, while the smart search works for the search of the whole table, I can't enable the smart search for the columns. Could someone please give me a hint what I can do to enable smart search also for the columns? Thank you in advance. enter image description here

output$shiny_table =
   DT::renderDT({

     # Show the filtered data table
     DT::datatable(

        # Call the filtered table as function
        data = table_filtered(),

        # Load and include extension modules
        extensions = c("FixedHeader"),

        # Each column has its own search box
        filter = list(position = "top",
                      clear = TRUE,
                      plain = TRUE),

        # Further options
        options = list(

           # Mark found search terms
           searchHighlight = TRUE,
           search = list(smart = TRUE, regex = TRUE, caseInsensitive = TRUE),

           # Special column properties
           columnDefs = list(
           
              # For specific columns: enable smart search
              list(targets = c("Title", "Authors", "Journal"),
                   search = list(smart = TRUE, regex = TRUE, caseInsensitive = TRUE)),

              # For specific columns: hide the search fields
              list(targets = c(" ", "Year", "Type", "Citations", "DOI"),
                   searchable = FALSE)
           )
        )
     )

   }, server = TRUE)
1

There are 1 answers

0
Stéphane Laurent On BEST ANSWER

There's no search option in columnDefs. You can try this:

library(DT)

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 value = $(this).val();",
  "    if(value !== '') {",
  "      var index = 1 + $inputs.index(this);", # add one if row names
  "      var column = table.column(index);",
  "      column.search(value, false, true, true).draw();", # options: regex, smart, case insensitive
  "    }",
  "  });",
  "}"
)

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
)

datatable(
  dat, filter = "top", 
  options = list(
    initComplete = JS(js),
    columnDefs = list(
      list(targets = 1, searchable = FALSE)
    )
  )
)