简体   繁体   中英

R Shiny: How to get the user input from the search box in a DT datatable?

I have developed a dashboard using the shiny and shinydashboard packages in R . The dashboard has a datatable produced with the DT package. At the top of the table, there is a search box that allows users to filter the rows of the table by typing in an input. Is it possible to get this input and use it in a reactive expression elsewhere in the dashboard?

Here is a toy example:

library(shiny)
library(shinydashboard)
library(DT)

shinyApp(
  ui = shinyUI(
    dashboardPage(
      dashboardHeader(title = "Example"),
      dashboardSidebar(sidebarMenu(id = 'tabs', menuItem("Tab1", tabName = 'Tab1'))), 
      dashboardBody(tabItems(tabItem(tabName = "Tab1", 
                                     fluidRow(column(width=6,box(DT::dataTableOutput('myTable'), width=NULL)),
                                              column(width=6,box(textOutput("myText"), width=NULL))))))
      )
  ),
  
  server = function(input, output, session){
    mytbl <- data.frame(Name = c('Matthew', 'Luke', 'John'), Grade=c(45, 20, 80))
    output$myTable <- DT::renderDataTable({DT::datatable(mytbl, rownames=FALSE)})
    output$myText <- renderText({ "The value entered in the seach box should appear here!" })
  }
)

Use this callback in the datatable function:

callback = JS(
  "table.on( 'search.dt', function () {",
    "Shiny.setInputValue( 'search', table.search() );",
  "} );"
)

Then in the Shiny server you have the user input in the reactive variable input$search .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM