Twitter bootstrap - Focus on textarea inside a modal on click

denislexic picture denislexic · Jul 24, 2012 · Viewed 85.3k times · Source

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.

Answer

scumah picture scumah · Jul 24, 2012

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/