【问题标题】:Select text / set focus in textInput在 textInput 中选择文本/设置焦点
【发布时间】:2018-06-07 23:31:18
【问题描述】:

背景

在我的应用程序中,我有一个登录页面,其中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)

【问题讨论】:

    标签: r shiny


    【解决方案1】:

    嗨,我认为在纯 Shiny 中没有办法。如果你愿意使用一点 JS,这里有一个简单的例子,它发送和处理从 Shiny 到 JS 的自定义消息 (more here)。它基本上只选择输入中的文本,但是一旦你在 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))
    

    【讨论】:

    • 完美,这就是我想要的。谢谢 + 1
    猜你喜欢
    • 2013-06-21
    • 2023-02-20
    • 2011-03-21
    • 1970-01-01
    • 2011-09-22
    • 2010-10-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多