Twitter bootstrap - Focus on textarea inside a modal on click

天涯浪子 提交于 2019-11-27 06:28:52
scumah

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/

Alexandre Roger

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.

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

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

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

Fiddle here (Click)

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

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

    });

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>

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.

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

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

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/

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.

Jeremias Pereira
<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>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!