如何在模态中设置对输入的关注

How to set focus on input in modal?

本文关键字:输入 设置 模态      更新时间:2023-09-26

我正试图在模态显示后将重点放在输入上。

到目前为止,我看到并尝试过的解决方案和链接:如何使用jQuery在页面加载时关注表单输入文本字段?,Jquery专注于输入字段,但它们都不起作用。

我的代码其实很简单:

$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);

使用显示的事件

$(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');
});

您可以尝试

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