I am trying to set focus to a textInput
in a modalDialog
in shiny. I am using shinyjs
. Following guidance from the shinyjs
documentation I came up with the following code which does not do what I expect:
library(shiny)
library(shinyjs)
jscode <- "
shinyjs.refocus = function(e_id) {
document.getElementById(e_id).focus();
}"
# Define UI for application that draws a histogram
ui <- fluidPage(
shinyjs::useShinyjs(),
shinyjs::extendShinyjs(text = jscode, functions = "refocus"),
# Application title
titlePanel("Old Faithful Geyser Data"),
# Sidebar with a slider input for number of bins
sidebarLayout(
sidebarPanel(
sliderInput("bins",
"Number of bins:",
min = 1,
max = 50,
value = 30),
actionButton("show", "Show Modal")
),
# Show a plot of the generated distribution
mainPanel(
plotOutput("distPlot")
)
)
)
# Define server logic required to draw a histogram
server <- function(input, output) {
output$distPlot <- renderPlot({
# generate bins based on input$bins from ui.R
x <- faithful[, 2]
bins <- seq(min(x), max(x), length.out = input$bins + 1)
# draw the histogram with the specified number of bins
hist(x, breaks = bins, col = 'darkgray', border = 'white')
})
observeEvent(input$show, {
showModal(ui = modalDialog(title = "my modal dialog",
textInput("text_1", label = "text 1"),
textInput("text_2", label = "text 2"),
js$refocus("text_1")))
})
}
# Run the application
shinyApp(ui = ui, server = server)
The modalDialog
is created with the two textInput
s but there is no focus on either input. How can I force input on the first input? I want to avoid that extra click to set the focus on the input. Thanks for any help.