Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Twitter bootstrap - Focus on textarea inside a modal on click

Just starting to play around with bootstrap and it's amazing.

I'm trying to figure this out. I have a textarea for feedback inside a modal window. It works great. But I want the focus to go on the textarea when you click on the button to activate the modal. And I can't seem to get it working.

Here is a fiddle: http://jsfiddle.net/denislexic/5JN9A/4/

Here is the code:

<a class="btn testBtn" data-toggle="modal" href="#myModal" >Launch Modal</a>  <div class="modal hide" id="myModal">   <div class="modal-header">     <button type="button" class="close" data-dismiss="modal">×</button>     <h3>Modal header</h3>   </div>   <div class="modal-body">       <textarea id="textareaID"></textarea>   </div>   <div class="modal-footer">     <a href="#" class="btn" data-dismiss="modal">Close</a>     <a href="#" class="btn btn-primary">Save changes</a>   </div> </div>​ 

Here is the JS

$('.testBtn').on('click',function(){     $('#textareaID').focus(); });​ 

To resume When I click on "Launch modal" I want the modal to show up and the focus to go on the textarea.

Thanks for any help.

like image 895
denislexic Avatar asked Jul 24 '12 16:07

denislexic


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 add focus to a modal?

As you can see, the entire website is keyboard accessible, means you can browse the website using just tab key, arrow keys and pressing enter key to open any menu or click anything. tab, shift + tab and enter key and focus should be trapped inside modal and should not go out after pressing tab key multiple times.


1 Answers

It doesn't work because when you click the button the modal is not loaded yet. You need to hook the focus to an event, and going to the bootstrap's modals page we see the event shown, that is fired when the modal has been made visible to the user (will wait for css transitions to complete). And that's exactly what we want.

Try this:

$('#myModal').on('shown', function () {     $('#textareaID').focus(); }) ​ 

Here's your fiddle updated: http://jsfiddle.net/5JN9A/5/


Update:

As @MrDBA notes, in Bootstrap 3 the event name is changed to shown.bs.modal. So, for Bootstrap 3 use:

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

New fiddle for Bootstrap 3: http://jsfiddle.net/WV5e7/

like image 64
scumah Avatar answered Oct 14 '22 17:10

scumah