thothal
thothal

Reputation: 20329

Select text / set focus in textInput

Background

In my app I have a login page with a textInput for the user name, a passwordInput for the password and an actionButton for submitting. If the password/username is not recognised, I show an error message. So far so good. I just want now to programatically select/highlight all the text in the username textInput, if the login did not work.

Question

How can I select the text in the username input form? I looked at updateTextInput but with this I can only change the value, not the selection. Do I need to fall back to javascript?

Code

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)

Upvotes: 3

Views: 810

Answers (1)

Mikolaj
Mikolaj

Reputation: 1495

Hi I think there is no way to do in in pure Shiny. If you're willing to use a bit of JS here's a simple example that sends and handles custom message from Shiny to JS (more here). It essentially only selects text in the input but once you're on the JS side, you can do basically anything you want. Cheers!

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))

Upvotes: 6

Related Questions