Search code examples
rshinyrenderdtmultiple-entries

How can I modify the inbuilt search bar of RenderDT in R Shiny to allow multiple entries separated by commas?


I have been trying to add multiple entries on the search bar of the renderdt table function on shiny. for example on the following code, instead of having a new search bar, i want to modify the one which is inbuilt in renderDT and allow it to take multiple entries, comma separated; for example setosa,virginica should bring rows with both setosa and virginica. I found solutions to add a new search bar but i wanted to know if i can modify this one accordingly. Any help regarding this would be highly appreciated.

if (interactive()) {
  library(shiny)
  library(DT)
  shinyApp(
    ui = fluidPage(fluidRow(column(12, DTOutput('tbl')))),
    server = function(input, output) {
      output$tbl = renderDT(
        iris, options = list(lengthChange = FALSE)
      )
    }
  )
}

i tried something like this, but this adds another search bar option and that is unnecessary

if (interactive()) {
  library(shiny)
  library(DT)
  
  shinyApp(
    ui = fluidPage(
      fluidRow(DTOutput('tbl'))
    ),
    server = function(input, output) {
      output$tbl = renderDT({
        data <- iris
        
        searchItems <- unlist(strsplit(input$search, ",")) # Split input string by commas
        searchItems <- trimws(searchItems) # Remove leading/trailing whitespace
        
        filteredData <- data[data$Species %in% searchItems, ]
        
        datatable(filteredData, options = list(lengthChange = FALSE))
      })
    }
  )
}

Solution

  • You can use this code:

    library(shiny)
    library(DT)
    
    callback <- function(sep) {
      sprintf('
    $("div.search").append($("#mySearch"));
    $("#mySearch").on("keyup redraw", function(){
      var splits = $("#mySearch").val().split("%s").filter(function(x){return x !=="";})
      var searchString = "(" + splits.join("|") + ")";
      table.search(searchString, true).draw(true);
    });
    ', sep)
    }
    
    ui <- fluidPage(
      tags$head(tags$style(HTML(".search {float: right;}"))),
      br(),
      tags$input(type = "text", id = "mySearch", placeholder = "Search"),
      DTOutput("dtable")
    )
    
    server <- function(input, output){
      
      output[["dtable"]] <- renderDT({
        datatable(
          iris[c(1, 2, 51, 52, 101, 102),],
          options = list(
            dom = "l<'search'>rtip"
          ),
          callback = JS(callback(","))
        )
      }, server = FALSE)
      
    }
    
    shinyApp(ui, server)
    

    enter image description here

    Personally I prefer the search builder:

    datatable(
      iris[c(1, 2, 51, 52, 101, 102),],
      extensions = "SearchBuilder",
      options = list(
        dom = "Qlfrtip", 
        searchbuilder = TRUE
      )
    )
    

    enter image description here