在 textInput 中选择文本/设置焦点

tho*_*hal 3 r shiny

背景

在我的应用程序中,我有一个登录页面,其中一个textInput用于用户名,一个passwordInput用于密码,一个actionButton用于提交。如果密码/用户名无法识别,我会显示一条错误消息。到目前为止,一切都很好。textInput如果登录不起作用,我现在只想以编程方式选择/突出显示用户名中的所有文本。

问题

如何选择用户名输入表单中的文本?我查看了updateTextInput,但这样我只能更改值,而不能更改选择。我需要回退到 JavaScript 吗?

代码

library(shiny)

is_valid_user <- function(uid, pwd) {
   FALSE
}

ui <- fluidPage(
   textInput("uid", "Username:"),
   passwordInput("pwd", "Password"),
   actionButton("ok", "Login"),
   div(textOutput("error"))
)

server <- function(input, output, session) {
    observeEvent(input$ok, {
                 if (!is_valid_user(req(input$uid), req(input$pwd))) {
                    output$error <- renderText("Username/password incorrect!")
                    ## TODO: select all text in textInput("uid"), but HOW?
                 }})
}

shinyApp(ui = ui, server = server)
Run Code Online (Sandbox Code Playgroud)

Mik*_*laj 6

嗨,我认为没有办法在纯粹的闪亮中做到这一点。如果您愿意使用一点 JS,这里有一个简单的示例,用于从 Shiny 向 JS 发送和处理自定义消息(更多信息请参见此处)。它本质上只选择输入中的文本,但一旦你在 JS 端,你基本上可以做任何你想做的事情。干杯!

library(shiny)

is_valid_user <- function(uid, pwd) {
  FALSE
}

ui <- fluidPage(
  tags$head(
    tags$script("
      Shiny.addCustomMessageHandler('selectText', function(message) {
        $('#uid').select();
      });
    ")
  ),
  textInput("uid", "Username:"),
  passwordInput("pwd", "Password"),
  actionButton("ok", "Login"),
  div(textOutput("error"))
)

server <- function(input, output, session) {
  observeEvent(input$ok, {
    if (!is_valid_user(req(input$uid), req(input$pwd))) {
      output$error <- renderText("Username/password incorrect!")
      ## TODO: select all text in textInput("uid"), but HOW?
      session$sendCustomMessage("selectText", "select")
    }})
}

shinyApp(ui = ui, server = server, options = list(port = 5555))
Run Code Online (Sandbox Code Playgroud)