Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Autofocus input in twitter bootstrap modal

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?

like image 845
eawer Avatar asked Feb 18 '13 16:02

eawer


People also ask

How do I set focus on bootstrap modal?

Answer: Use the jQuery . focus() method You can simply use the jQuery . focus() method to set the focus on the first input box or textarea inside the Bootstrap modal when it is loaded upon activation.

How do you set focus on modal?

tab, shift + tab and enter key and focus should be trapped inside modal and should not go out after pressing tab key multiple times.


2 Answers

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(); }); 
like image 136
nc. Avatar answered Sep 20 '22 08:09

nc.


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!

like image 40
nooweel Avatar answered Sep 23 '22 08:09

nooweel