【问题标题】:How to set focus on input in modal?如何在模态中设置焦点输入?
【发布时间】:2014-09-24 16:01:00
【问题描述】:

我正在尝试在模式显示后将焦点设置在输入上。

到目前为止我看到并尝试过的解决方案和链接:How to focus on a form input text field on page load using jQuery?Jquery Focus on input field,但它们都不起作用。

我的代码其实很简单:

$input = $("#letter-change-text").find("input[type='text']");
$input.val($.trim("I am just testing!!"));
$("#letter-change-text").modal('show');
$input.focus(); // this should focus the textbox in order to allow immediately input by the user

您可以在 JSfiddle 中查看此问题。

我也试过了,没有成功:

setTimeout(function(){
   $input.focus();
}, 0);

【问题讨论】:

  • 我认为您必须等到动画完成才能聚焦输入。尝试增加setTimeout中的等待时间
  • 在显示模式后尝试获取输入 - jqueryui 可能会复制元素。

标签: javascript jquery jquery-ui


【解决方案1】:

使用显示的事件

$(function(){
    $input = $("#letter-change-text").find("input[type='text']");
    $input.val($.trim("I am just testing!!"));
    $('#letter-change-text').on('shown.bs.modal', function (e) {
       $input.focus();
    }).modal('show');
});

【讨论】:

  • 好吧,我刚刚将我的帖子编辑为该解决方案..但我会再次编辑并接受您的回答。
  • 你为什么要编辑帖子以获得解决方案,这就是答案的目的......
  • 你能解释一下第 4 行的“shown.bs.modal”是什么吗?
  • @Amitkumar 阅读引导文档。他们触发事件
【解决方案2】:

你可以试试

$("#dgRejectSalvage").on('shown.bs.modal', function () {
    $(this).find('#RejectionReason').focus();
});

【讨论】:

    猜你喜欢
    • 2018-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-28
    • 2011-06-06
    相关资源
    最近更新 更多