Within Shiny I'd like to be able to set the focus on the first field of a modalDialog which happens to be numericInput.
In the example (which was based on the code from Shiny: set focus to input in modalDialog I can set the focus to the SelectInput but not the numericInput. Any suggestions of a solution or where I may be able to find documentation that explains this would be appreciated.
Thanks
library(shiny)
## create an event listener at <body> which fires as soon as the modal is shown
## sets the focus to the first text element (adapt if needed)
jscode <- HTML("$('body').on('shown.bs.modal', (x) =>
$(x.target).find('input[type=\"text\"]:first').focus())")
# Define UI for application that draws a histogram
ui <- fluidPage(
# Application title
titlePanel("Old Faithful Geyser Data"),
tags$header(tags$script(type = "text/javascript", jscode)),
# 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",
numericInput("num_1", label = "num 1", value = 1),
selectInput("select_1", label = "select 1", choices = c('1','2','3')),
textInput("text_2", label = "text 2")
))
})
}
# Run the application
shinyApp(ui = ui, server = server)