1

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)
Jareem
  • 11
  • 2
  • Change `input[type=\"text\"]:first` to `input[type=\"number\"]:first`. Unsurprisingly, Javascript regards text inputs as text and numeric inputs as numeric. – Limey Aug 04 '22 at 10:49
  • Thanks very much Limey!!! I tried numeric but not number. Do you know where this is documented? – Jareem Aug 04 '22 at 22:47
  • [This](https://www.javatpoint.com/html-form-input-types) looks to be helpful, though it's not a formal specification. – Limey Aug 07 '22 at 08:15
  • Thanks Limey. Gives me a reference point - much appreciated . Thanks for answering my question - Jareem :) – Jareem Aug 09 '22 at 00:23

0 Answers0