Reputation: 33
I have a series of textInputs in R Shiny and want to get and display the ID of the text box with focus, i.e. the one in which the cursor is flashing, in a textOutput.
I'm trying to do this in JavaScript with little success.
This is what I've been working with:
ui <- fluidPage(
tags$script(' Shiny.setInputValue("focused.element", $(document.activeElement )) '),
textInput(inputId = "text1", label = NULL, value = ""),
textInput(inputId = "text2", label = NULL, value = ""),
textInput(inputId = "text3", label = NULL, value = ""),
textInput(inputId = "text4", label = NULL, value = ""),
textOutput("output1")
)
server <- function(input, output, session) {
output$output1 <- renderText({ input$focused.element })
}
I would like this to display "text1" when the cursor is in the first textInput, text2 when it's in the second, etc...
Right now, no text is displayed from output1. Any help would be appreciated!
Upvotes: 2
Views: 543
Reputation: 84649
This ?
library(shiny)
ui <- fluidPage(
tags$script('$(document).ready(function(){ $("input").on("focus", function(e){ Shiny.setInputValue("focusedElement", e.target.id);}); }); '),
textInput(inputId = "text1", label = NULL, value = ""),
textInput(inputId = "text2", label = NULL, value = ""),
textInput(inputId = "text3", label = NULL, value = ""),
textInput(inputId = "text4", label = NULL, value = ""),
textOutput("output1")
)
server <- function(input, output, session) {
output$output1 <- renderText({ input$focusedElement })
}
shinyApp(ui, server)
Upvotes: 2