Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set the focus for a particular field in a Bootstrap modal, once it appears

People also ask

How do I set focus on Bootstrap modal?

Answer: Use the jQuery . focus() method You can simply use the jQuery . focus() method to set the focus on the first input box or textarea inside the Bootstrap modal when it is loaded upon activation.

How do you set focus on modal?

tab, shift + tab and enter key and focus should be trapped inside modal and should not go out after pressing tab key multiple times.

How does Bootstrap modal trap focus?

Bootstrap 4: by open the first modal, the focus is a trap inside it (you can move the focus with tab key and you will never focus element outside the modal). When you open the second modal the focus is a trap inside it and again you can't focus outside element (this is right).


Try this

Here is the old DEMO:

EDIT: (Here is a working DEMO with Bootstrap 3 and jQuery 1.8.3)

$(document).ready(function() {
    $('#modal-content').modal('show');
    $('#modal-content').on('shown', function() {
        $("#txtname").focus();
    })
});

Starting bootstrap 3 need to use shown.bs.modal event:

$('#modal-content').on('shown.bs.modal', function() {
    $("#txtname").focus();
})

Just wanted to say that Bootstrap 3 handles this a bit differently. The event name is "shown.bs.modal".

$('#themodal').on('shown.bs.modal', function () {
   $("#txtname").focus();
});

or put the focus on the first visible input like this:

.modal('show').on('shown.bs.modal', function ()
{
    $('input:visible:first').focus();
})

http://getbootstrap.com/javascript/#modals


I am using this in my layout to capture all modals and focus on the first input

  $('.modal').on('shown', function() {
     $(this).find('input').focus();
  });

I had the same problem with bootstrap 3, focus when i click the link, but not when trigger the event with javascript. The solution:

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

Probably it´s something about the animation!