Autofocus input in twitter bootstrap modal

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

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!


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()
})