首页 > 解决方案 > 使用 shinyjs / javascript 在 selectizeInput 中显示下拉选项

问题描述

在我的应用程序中,我有一个搜索栏,用于过滤相关 selectizeInput 中的选项。当用户在搜索栏中输入内容并单击搜索图标/按下回车键时,我希望显示下面下拉列表中的选项(类似于我单击 selectizeInput),因此用户很清楚他们的搜索被处理。

我能够使用这篇文章来弄清楚如何从 JavaScript 中引用下拉列表。但是,我正在努力编写扩展下拉列表所需的 JS 代码。

我尝试了 .click 方法,并尝试使用此处此处描述的 selectize API 方法。但是,后一个示例中提供的代码太少了,我似乎无法复制它。

我在下面粘贴了一个 MWE。我更喜欢使用 selectize API 方法,但我对任何 Javascript 方法持开放态度,这些方法将在输入搜索时模拟“单击并展开”下面的下拉列表。这是我第一次在 SO 上发帖,所以如果我错过了什么,我深表歉意!非常感谢您的帮助!

library(shiny)
library(shinyWidgets)
library(shinyjs)

ui <- fluidPage(

    useShinyjs(),  # Include shinyjs
    
    #the search bar that will hopefully open the below dropdown when the user clicks "enter"
    searchInput(
      inputId = "search_box", label = "Search", placeholder = "",
      btnSearch = icon("search"), btnReset = NULL),
    
    selectizeInput("dropdown","Select from dropdown", multiple = T,
                   choices = c("dog 1","dog 2","dog 3","cat 1","cat 2","cat 3")),
    
    #accessing the selectize input with javascript
    actionButton("access_selectize","Access selectize with js")
    
    
)

server <- function(input, output) {

    #confirming that element is properly accessed with JS
    observeEvent(input$access_selectize,{
        runjs('alert($("#dropdown :selected").text())')
    })
    
    #this part does not work... 
    observeEvent(input$search_box, {
        runjs('
        var $select = $("#dropdown :selected").selectize(options);
        $select[0].open();
        ')
    })
}

# Run the application 
shinyApp(ui = ui, server = server)

标签: javascriptrshinyshinyjs

解决方案


推荐阅读