【发布时间】:2020-04-16 23:16:16
【问题描述】:
加载我的 R Shiny 应用程序后,我想将焦点设置到 selectInput 元素,以便用户可以立即通过上下箭头选择一个项目并按 Enter。
我试图捕获 JavaScript load 事件,将其发送到 R,然后使用 Shiny.addCustomMessageHandler 设置 selectInput 元素的焦点。
作为中间步骤,我还尝试使用来自actionButton 的点击事件来触发元素焦点。虽然我认为大部分部分都应该在代码中,但load 事件不会被传输到服务器,并且焦点部分会被 JavaScript 拾取。
这篇帖子focusing the cursor in textArea after clicking an action button in shiny 也没有帮助我到达终点线。
这是我目前所拥有的:
library(shiny)
ui <- fluidPage(
tags$head(tags$script('
window.addEventListener("load", function(){
alert("Loaded");
Shiny.setInputValue("loaded", 1) // new identical function to Shiny.onInputChange
});
')),
tags$head(tags$script('
Shiny.addCustomMessageHandler("focus", function(null) {
document.getElementById("select").focus()
});
')),
headerPanel("Focus", windowTitle = "Focus"),
fluidRow(
column(width = 2, class = "panel",
selectInput("select", label = "Your Choice", choices = c("Choice 1", "Choice 2"), selectize = TRUE),
actionButton("click", "Click")
),
column(width = 10,
textOutput("text")
)
)
)
server = function(input, output, session) {
observeEvent(input$loaded, {
session$sendCustomMessage("focus",list(NULL))
print("Loaded")
})
observeEvent(input$select, {
print("Selected")
})
observeEvent(input$click, {
session$sendCustomMessage("focus",list(NULL))
print("Clicked")
})
output$text <- renderText({
})
}
shinyApp(ui = ui, server = server)
感谢您的帮助。
【问题讨论】: