You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Shiny的modalDialog中设置numericInput获取焦点?

Shiny中让modalDialog的numericInput自动获取焦点的解决方案

问题出在你原有的JavaScript选择器只针对type="text"的输入框,而Shiny的numericInput渲染后对应的HTML元素是input[type="number"],所以需要调整选择器来匹配这类输入框。

修改后的JavaScript代码

把原来的jscode替换为以下内容,它会在modal显示时自动聚焦到其中第一个type="number"的输入框:

$('body').on('shown.bs.modal', (x) => 
  $(x.target).find('input[type="number"]:first').focus()
)

如果需要同时兼容numericInput、textInput和selectInput,可以扩展选择器,确保第一个可输入元素获得焦点:

$('body').on('shown.bs.modal', (x) => 
  $(x.target).find('input[type="number"], input[type="text"], select').first().focus()
)

完整可运行代码

library(shiny)

# 修改后的事件监听代码,适配numericInput
jscode <- HTML("$('body').on('shown.bs.modal', (x) => 
                   $(x.target).find('input[type=\"number\"]:first').focus())")

ui <- fluidPage(
  titlePanel("Old Faithful Geyser Data"),
  tags$header(tags$script(type = "text/javascript", jscode)),
  sidebarLayout(
    sidebarPanel(
      sliderInput("bins",
                  "Number of bins:",
                  min = 1,
                  max = 50,
                  value = 30),
      actionButton("show", "Show Modal")
    ),
    mainPanel(
      plotOutput("distPlot")
    )
  )
)

server <- function(input, output) {
  output$distPlot <- renderPlot({
    x    <- faithful[, 2]
    bins <- seq(min(x), max(x), length.out = input$bins + 1)
    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")
    ))
  })
}

shinyApp(ui = ui, server = server)

原理说明

  • Bootstrap的modal会在完全显示后触发shown.bs.modal事件,我们通过监听这个事件来执行聚焦操作
  • $(x.target)指向当前弹出的modal元素,通过find()方法定位到其中第一个type="number"的输入框
  • 调用focus()方法让该输入框获得焦点

内容的提问来源于stack exchange,提问作者Jareem

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 05:45:40