Twitter bootstrap - Focus on textarea inside a modal on click

86,556

Solution 1

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/

Solution 2

I wanted to have a declarative version of this, so I went with the following :

$(document).ready(function() {
    $(".modal").on('shown.bs.modal', function () {
        $("[data-modalfocus]", this).focus();
    });
});

You can then simply add a data-modalfocus property to your field, like so :

<input type="text" data-modalfocus />

And when the modal pops-up, your field will get focus.

Solution 3

Bootstrap3

$(window.document).on('shown.bs.modal', '.modal', function() {
    window.setTimeout(function() {
        $('[autofocus]', this).focus();
    }.bind(this), 100);
});

Bootstrap 2

$(window.document).on('shown', '.modal', function() {
    window.setTimeout(function() {
        $('[autofocus]', this).focus();
    }.bind(this), 100);
});

Solution 4

You can use the autofocus html element to set the autofocus.

<textarea id="textareaID" autofocus="" ></textarea>

Fiddle here (Click)

Solution 5

As mentioned in one of the comments you need to remove fade from your modal. So this works for me:

 <div id="myModal" class="modal">
    ...
    <textarea class="form-control" rows="5" id="note"></textarea>
  </div>

  <script>
    $('#myModal').on('shown.bs.modal', function () {
        $('#note').focus();
    })
  </script>
Share:
86,556
denislexic
Author by

denislexic

Started learning programming on youtube and forums. Now I am addicted to it.

Updated on July 05, 2022

Comments

  • denislexic
    denislexic almost 2 years

    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.

  • Jim Miller
    Jim Miller over 11 years
    Heads-up: If your modal has a 'fade' property, this approach may not work, depending on what seem to be some pretty obscure timing conditions (i.e., where the modal doesn't exist enough to accept the focus request until it's completely faded in). I was only able to set focus on a modal item by dropping the fade property, at which point I could just do a $('#textareaID').focus() call right after the .show() call. YMMV, I suppose...
  • chrisb
    chrisb over 11 years
    Thanks Jim, it was really annoying me why the focus wasn't being set but it was because I had a fade in. Would be great if there were a work around.
  • scumah
    scumah over 11 years
    @chrisb you mean adding a fade class to your modal? It's working for me: jsfiddle.net/5JN9A/16 If I could see a failing example I could try to find a workaround :P
  • MrDBA
    MrDBA almost 11 years
    FYI Bootstrap v3 has changed the event name to shown.bs.modal
  • Leniel Maccaferri
    Leniel Maccaferri almost 11 years
    StackOverflow is so awesome that I got here and @MrDBA commented 2 hours ago about Bootstrap change for v3. Thanks buddy! :) Almost realtime coding FTW!
  • Smern
    Smern over 10 years
    you should include some comments on exactly what you did rather than force people to try and hunt down the changes
  • Stephen Smith
    Stephen Smith over 10 years
    For some reason the $('#passwordModal').focus(); isn't setting focus to my <input id="passwordModal" .... >. Even running in console after the modal is way done with transitions.
  • Davis
    Davis over 10 years
    All responses did not work for some reason.. so the above post is my solution just someone has the same issue as me.
  • Davis
    Davis over 10 years
    Tested in jQuery 1.10.2 | Bootstrap v3.0.3
  • mgPePe
    mgPePe over 10 years
    If I have content loaded remotely to the modal, and in that content I have $('document').ready(function(){ isn't that supposed to work?
  • nevermind
    nevermind over 9 years
    This works only for the first time. When dialog is closed (hidden) and shown again, field doesn't receive focus.
  • S3RK
    S3RK almost 9 years
    Pay attention to event name. It must be 'shown.bs.modal', not 'show.bs.modal'. And btw setting focus from console in Chrome doesn't work because page window is not active. To work around it you can use setTimeout
  • Yves Martin
    Yves Martin over 8 years
    Why not use direct $('#myField').focus ?
  • J.J
    J.J over 8 years
    @YvesMartin You are right, There should only be one id with the same name, and there for it should be selected as you point out
  • Chris Broski
    Chris Broski over 7 years
    My modal fades in so I had to increase the timeout to 500ms, but other than that, this worked great.
  • Aaron Hudon
    Aaron Hudon over 7 years
    Excellent general-purpose fix for Bootstrap3. HIGH ENERGY!
  • Alexis Wilke
    Alexis Wilke about 7 years
    Yes! That works. I was trying the "shown.bs.modal" directly on the modal (i.e. "#modalName") and the event was not being triggered. Moving it to the body works. Unfortunate since that means you do not really know which modal gets triggered without testing that... or as you do, set the focus of the first item of any modal you have.