如何在R Shiny的DT组件中通过代码程序化输入搜索文本?
Sync Text Input with DT's Built-in Search Box
I get exactly what you're asking for—you want the text from your textInput('search2') to automatically populate DT's native search box and trigger the search, without having to handle data filtering yourself. Here's how to make that work smoothly:
The core trick is using Shiny's updateDT() function to send the value from your text input directly to DT's built-in search field. This way, you're leveraging DT's own search functionality entirely, just routing your external input to it.
Full Working Code
library(shiny) library(DT) shinyApp( ui = fluidPage( textInput('search2', "Search 2"), DTOutput('dt') ), server = function(input, output, session) { # Render the DT table as usual output$dt = renderDT( iris, # Optional: Keep DT's native search box visible if you want both inputs # If you don't want to show DT's search box, add searching = FALSE here options = list(searching = TRUE) ) # Sync textInput to DT's search box and trigger search observe({ updateDT(session, 'dt', search = input$search2) }) } )
Key Details:
- The
observe()block listens for changes toinput$search2every time the user types something. updateDT()sends the current value ofsearch2to DT's internal search state, which immediately triggers the table's native search action—no extra filtering code needed.- If you don't want DT's original search box to be visible, just add
searching = FALSEto theoptionsargument inrenderDT(). The sync will still work perfectly, using only your custom text input.
内容的提问来源于stack exchange,提问作者Vlad
相关产品推荐
相关产品推荐

