Twitter bootstrap-Centrarse en textarea dentro de un modal en clic


Acaba de empezar a jugar con bootstrap y es increíble.

Estoy tratando de resolver esto. Tengo un área de texto para comentarios dentro de una ventana modal. Funciona muy bien. Pero quiero que el foco vaya en el área de texto cuando haga clic en el botón para activar el modal. Y parece que no puedo hacerlo funcionar.

Aquí hay un violín: http://jsfiddle.net/denislexic/5JN9A/4 /

Aquí está el código:

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

Aquí está la JS

$('.testBtn').on('click',function(){
    $('#textareaID').focus();
});​

To reanudar Cuando hago clic en "Launch modal" quiero que el modal aparezca y el enfoque vaya al área de texto.

Gracias por cualquier ayuda.

Author: user2771704, 2012-07-24

13 answers

No funciona porque al hacer clic en el botón el modal no está cargado todavía. Necesitas enganchar el foco a un evento, y yendo a la página de modales de bootstrap vemos el evento shown, que is fired when the modal has been made visible to the user (will wait for css transitions to complete). Y eso es exactamente lo que queremos.

Prueba esto:

$('#myModal').on('shown', function () {
    $('#textareaID').focus();
})
​

Aquí está tu violín actualizado: http://jsfiddle.net/5JN9A/5 /


Actualización:

Como señala @MrDBA, en Bootstrap 3 el nombre del evento es cambiado a shown.bs.modal. Tan, para Bootstrap 3 use:

$('#myModal').on('shown.bs.modal', function () {
    $('#textareaID').focus();
})

Nuevo violín para Bootstrap 3: http://jsfiddle.net/WV5e7/

 202
Author: scumah,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:18:23

Quería tener una versión declarativa de esto, así que fui con lo siguiente :

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

Entonces simplemente puede agregar una propiedad data-modalfocus a su campo, así:

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

Y cuando aparezca el modal, tu campo se enfocará.

 19
Author: Alexandre Roger,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-12-16 11:57:39

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);
});
 11
Author: Jonas Sciangula Street,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-06-08 15:11:40

Puede utilizar el elemento html autofocus para establecer el enfoque automático.

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

El violín aquí (Clic)

 4
Author: Chancho,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-12-26 22:42:00

Si su modal tiene la propiedad 'fade':

Esto funcionará, pero es posible que tenga que ajustar la duración del tiempo de espera y, obviamente, los ID cuando sea necesario:

$("#ID-of-modal").on('show', function(event){
                window.setTimeout(function(){
                  $(event.currentTarget).find('input#ID-of-input').first().focus()
                }, 0175);
              });
 1
Author: Semaj Nekeerv,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-08-23 18:09:35

Yo estaba teniendo problemas importantes en Chrome... Espero que esto ayude a alguien.

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

    });
 1
Author: Davis,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-12-26 16:01:40

Como se mencionó en uno de los comentarios, debe eliminar fade de su modal. Así que esto funciona para mí:

 <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>
 1
Author: tokhi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-04-27 16:06:43

Quería algo un poco más genérico

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

Con esto, doy cualquier control que quiera a la clase CSS firstInput. Hay un ligero retraso en el establecimiento de enfoque que le da un cierto estilo.

 1
Author: John Grabauskas,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-02-19 21:46:22

No se por qué, pero la solución elegida no funciona para mí.. En su lugar, utilizo el siguiente fragmento de código:

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

Sé que no es tan bonito, pero al menos funciona.. Bootstrap v2. 3. 0

 0
Author: nKognito,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-08-26 10:54:08

Si está utilizando bootstrap v3 y está utilizando tanto el diálogo modal como el editor de texto wysihtml5, lo siguiente funciona (suponiendo que #basic es el ID de su forma modal):

    $('#basic').on('shown.bs.modal', function () {
    editor.composer.element.focus()
})
 0
Author: Ryan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-01-28 22:52:32

Adjuntar el evento directamente a la pantalla modal no funcionó para mí. Estoy usando este código en su lugar:

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

Con este código solo necesito cambiar MyField por el id del control que quiero tener el foco, también me permite definir el foco para múltiples pantallas modales, tengo algo así como:

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

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

 0
Author: Juan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-07-23 13:57:16

Encontrado haciendo:

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

Funcionó bien, ya que solo encuentra el primer control de forma en lugar de necesitar un id específico, etc. Ser justo lo que se necesita la mayor parte del tiempo.

 0
Author: SimonKiteley,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-08-12 13:30:58
<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>
 -1
Author: Jeremias Pereira,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-10-11 12:24:54