Shtirlits Shtirlits - 1 year ago 227
jQuery Question

Autofocus input in twitter bootstrap modal

Hi everyone!

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.

Thanks in advance!

nc. nc.
Answer Source

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('', function() {
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download