denislexic
denislexic

Reputation: 11342

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.

Upvotes: 70

Views: 88017

Answers (13)

Alexandre Roger
Alexandre Roger

Reputation: 1041

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.

Upvotes: 23

Jonas Sciangula Street
Jonas Sciangula Street

Reputation: 1892

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

Upvotes: 11

John Grabauskas
John Grabauskas

Reputation: 298

I wanted something a bit more generic

    $(window.document).on('shown.bs.modal', '.modal', function () {
        var timer = window.setTimeout(function () {
            $('.firstInput', this).focus();
            typeof timer !== 'undefined' && window.clearTimeout(timer);
        }.bind(this), 100);
    });

With this, I give whatever control I want the CSS class firstInput. There is a slight delay in setting focus that gives it a certain flair.

Upvotes: 1

SimonKiteley
SimonKiteley

Reputation: 369

Found doing:

$(document).on('shown.bs.modal', function () {
  $(this).find('.form-control:visible:first').focus();
});

Worked well as it just finds the first form-control rather than needing a specific id etc. Be just what is needed most of the time.

Upvotes: 0

J.J
J.J

Reputation: 1001

Attaching the event directly to the modal screen didn't work for me. I'm using this code instead:

$('body').on('shown.bs.modal', '.modal', function () {
  $('[id$=myField]').focus();
})

With this code I only need to change myField for the id of the control I want to have the focus, it also allows me to define the focus for multiple modal screens, I have something like:

      $('body').on('shown.bs.modal', '.modal', function () {
        $('[id$=YesCancel]').focus();
        $('[id$=YesInverted]').focus();
        $('[id$=cancelAddCustomer]').focus();
        $('[id$=closeHistoryModal]').focus();
      });

Source http://xcellerant.net/2014/08/06/set-focus-on-a-field-when-showing-a-bootstrap-3-modal/

Upvotes: 0

tokhi
tokhi

Reputation: 21618

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>

Upvotes: 1

scumah
scumah

Reputation: 6383

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/

Upvotes: 209

Ryan
Ryan

Reputation: 804

If you are using bootstrap v3 and you are using both modal dialog and wysihtml5 text editor the following works (assuming #basic is the ID of your modal form):

    $('#basic').on('shown.bs.modal', function () {
    editor.composer.element.focus()
})

Upvotes: 0

Azox
Azox

Reputation: 1940

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

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

Fiddle here (Click)

Upvotes: 4

Davis
Davis

Reputation: 3017

I was having major issues in chrome... I hope this helps someone.

//When user clicks link
$('#login-modal-link').on('click',function() {
        setTimeout(function(){
                //If modal has class
            if ($('#login-modal').hasClass('modal')) {
                //Whatever input you want to focus in
                $('#user_login_modal').focus();
            }
        },100);

    });

Upvotes: 1

Jeremias Pereira
Jeremias Pereira

Reputation: 1

<a href="" id="btnmoverCategoriaRaiz">Mover para a raiz...</a> 
      <script>
         $(function(){
            $("#btnmoverCategoriaRaiz").click(function(){
                $("#novoPlaylist").modal();
                return false;
            });
         });

       </script>    
 <div id="novoPlaylist" class= "modal  hide">
          <div class="modal-header">
            <h3>Novo Playlist</h3>
          </div>
          <div class="modal-body">
            <form class="form-horizontal">
              <?echo $form->input("Playlist.nome", array("label"=>"Nome:")) ?>
            </form>
          </div>
              <div class="modal-footer">
                 <a href="javascript:;" class="btn" data-dismiss="modal">Cancelar</a>
                 <a href="javascript:;" class="btn btn-primary" id="SalvarNomePlaylist" data-loading-text="Aplicando..."> Savar</a>
              </div>
      </div>

Upvotes: -1

nKognito
nKognito

Reputation: 6363

I don't know why, but the choosed solution doesn't work for me.. I use the following code snippet instead:

$('#annul-modal').on('show', function() {
    setTimeout(function() {$('textarea:first', '#annul-form').focus();}, 400);
});

I know it isn't so pretty but at least it works.. Bootstrap v2.3.0

Upvotes: 0

Semaj Nekeerv
Semaj Nekeerv

Reputation: 131

If your modal has the 'fade' property:

This will work but you might have to adjust the duration of the timeout and obviously the IDs where needed:

$("#ID-of-modal").on('show', function(event){
                window.setTimeout(function(){
                  $(event.currentTarget).find('input#ID-of-input').first().focus()
                }, 0175);
              });

Upvotes: 1

Related Questions