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?
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:
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 theshown.bs.modal
eventIs your modal markup dynamically generated?
Register an event handler on the entire document for the
shown.bs.modal
event.try removing tabindex="-1" and it works fine.
Hope this helps!
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
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.Above answers are somewhat outdated for latest Bootstrap versions.
Below is excerpted from: http://getbootstrap.com/javascript/#modals