Autofocus input in twitter bootstrap modal

懵懂的女人 提交于 2019-11-26 16:38:47

问题


I have such problem - I need to autofocus some element inside twitter bootstrap modal (after it shows). The tricky part is here - content of this modal is loaded using 'data-remote' (jQuery.load method) from separate HTML file, so

$(document).on('shown', ".modal", function() {
    $('[autofocus]', this).focus();
});

works only if modal was loaded before.
The question is - how to make autofocus work at the first time modal loads?


回答1:


I'm using Bootstrap 3.0 (hopefully, this works with 3.1 as well).

We had to use tabindex="-1" because that allows the ESC key to close the modal.

So I was able to fix this issue using:

// Every time a modal is shown, if it has an autofocus element, focus on it.
$('.modal').on('shown.bs.modal', function() {
  $(this).find('[autofocus]').focus();
});



回答2:


try removing tabindex="-1" and it works fine.

<div class="modal fade" id="modalID" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">

<div class="modal fade" id="modalID" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">

Hope this helps!




回答3:


I couldn't get @nc's solution working on my app. It didn't see modals that were added later. This worked for me though

$(document).on('shown.bs.modal', '.modal', function() {
  $(this).find('[autofocus]').focus();
});

As Frank Fang points out, you should use this if you are using a newer version of Bootstrap that doesn't rely on the autofocus HTML attribute.

$('#myModal').on('shown.bs.modal', function () {
  // get the locator for an input in your modal. Here I'm focusing on
  // the element with the id of myInput
  $('#myInput').focus()
})



回答4:


Above answers are somewhat outdated for latest Bootstrap versions.

Below is excerpted from: http://getbootstrap.com/javascript/#modals

Due to how HTML5 defines its semantics, the autofocus HTML attribute has no effect in Bootstrap modals. To achieve the same effect, use some custom JavaScript:

$('#myModal').on('shown.bs.modal', function () {
  $('#myInput').focus()
})



回答5:


You have an input with the autofocus attribute you want focused when the bootstrap modal is shown.

Is your modal markup available when JavaScript is loaded?

Register an event handler on all .modal elements for the shown.bs.modal event

$('.modal').on('shown.bs.modal', function() {
  $(this).find('[autofocus]').focus();
});

Is your modal markup dynamically generated?

Register an event handler on the entire document for the shown.bs.modal event.

$(document).on('shown.bs.modal', '.modal', function () {
    $(this).find('[autofocus]').focus();
});


来源:https://stackoverflow.com/questions/14940423/autofocus-input-in-twitter-bootstrap-modal

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!