0

I am new to shiny and had a query if something was possible to do. I want to allow the user to input text search terms and return the rows of the dataframe where the users’ search term appears in the description.

As I am new here, I am unsure as to the best and clearest way to describe the problems I’ve been having so I can add in any more information if needed. Any suggestions would be greatly appreciated please. Thankyou.

rjrons42
  • 3
  • 2
  • Why don't you simply use the search input of your `datatable()` (upper right corner)? Also see [this](https://stackoverflow.com/questions/41597062/r-download-filtered-datatable). – ismirsehregal May 24 '19 at 11:54
  • Thanks for your reply and the recommendation. The search input only allows me to search by one value at a time. I was hoping to find a way to search for all rows that could contain 1 or more of multiple different search terms, and then return these rows altogether? – rjrons42 May 24 '19 at 13:08
  • You can search for multiple items separated by space. – ismirsehregal May 24 '19 at 13:29
  • Thanks, I tried searching that way but it only returns rows that contain all of the values entered in the search box. If I entered computer, audio and mp3, I want to return all rows that contain at least 1 of those terms. I'd still like to return rows that might contain only audio and mp3, but don't contain computer as well. – rjrons42 May 24 '19 at 13:35

1 Answers1

1

You can use a regular expression in the search input by setting the option search$regex to TRUE:

datatable(iris[c(1,2,51,52,101,102),], 
          options = 
            list(
              search = list(regex = TRUE)
            )
)

enter image description here

Another solution (hit 'Return' to run the search):

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('keypress', function(e){",
  "    if(e.which == 13){",
  "      var keywords = input.val().split(' '), filter ='';",
  "      for(var i=0; i<keywords.length; i++){",
  "        filter = (filter !== '') ? filter + '|' + keywords[i] : keywords[i];",
  "      }",
  "      table.search(filter, true, false).draw();",
  "    }",
  "  });",
  "}"
)


datatable(iris[c(1,2,51,52,101,102),], 
          options = 
            list(initComplete = JS(js)
          )
)

enter image description here

Stéphane Laurent
  • 75,186
  • 15
  • 119
  • 225