Twitter bootstrap - Focus on textarea inside a modal on click

JavascriptJqueryTwitter BootstrapFocusTextarea

Javascript Problem Overview


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.

Javascript Solutions


Solution 1 - Javascript

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 - Javascript

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 - Javascript

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 - Javascript

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

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

Fiddle here (Click)

Solution 5 - Javascript

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

Solution 6 - Javascript

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

	});

Solution 7 - Javascript

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>

Solution 8 - Javascript

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.

Solution 9 - Javascript

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

Solution 10 - Javascript

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

Solution 11 - Javascript

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/

Solution 12 - Javascript

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.

Solution 13 - Javascript

<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>

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiondenislexicView Question on Stackoverflow
Solution 1 - JavascriptscumahView Answer on Stackoverflow
Solution 2 - JavascriptAlexandre RogerView Answer on Stackoverflow
Solution 3 - JavascriptJonas Sciangula StreetView Answer on Stackoverflow
Solution 4 - JavascriptChanchoView Answer on Stackoverflow
Solution 5 - JavascriptSemaj NekeervView Answer on Stackoverflow
Solution 6 - JavascriptDavisView Answer on Stackoverflow
Solution 7 - JavascripttokhiView Answer on Stackoverflow
Solution 8 - JavascriptJohn GrabauskasView Answer on Stackoverflow
Solution 9 - JavascriptnKognitoView Answer on Stackoverflow
Solution 10 - JavascriptRyanView Answer on Stackoverflow
Solution 11 - JavascriptJ.JView Answer on Stackoverflow
Solution 12 - JavascriptSimonKiteleyView Answer on Stackoverflow
Solution 13 - JavascriptJeremias PereiraView Answer on Stackoverflow