142

I load a dynamic bootstrap modal and it contains few text inputs. The issue i face that i want the cursor to focus on the first input in this modal, and this is not happening by default.
So i wrote this code to do it:

$('#modalContainer').on('show', function () {
   $('input:text:visible:first').focus();
});

But now it focus on the in the input for a moment then go away automatically, why this is happening and how to solve?

Amr Elgarhy
  • 66,568
  • 69
  • 184
  • 301
  • 2
    Can you provide a demo on http://www.jsfiddle.net? – Ram Mar 06 '13 at 12:54
  • Try setting a timeout for it, something else might be interfering. `setTimeout(function() { /* Your code */ }, 100);` – qwerty Mar 06 '13 at 12:59
  • can you try this for me... var index = 0; $('#modalContainer').on('show', function () { index = 1; }); if(index){ $('input:text:visible:first').focus(); } – chirag ghiyad Mar 06 '13 at 13:03
  • Possible duplicate of [Twitter bootstrap modal input field focus](http://stackoverflow.com/questions/15474862/twitter-bootstrap-modal-input-field-focus) – Muhammad Rehan Saeed Oct 13 '15 at 13:48

18 Answers18

227

@scumah has the answer for you: Twitter bootstrap - Focus on textarea inside a modal on click

For Bootstrap 2

modal.$el.on('shown', function () {
$('input:text:visible:first', this).focus();
});  

Update: For Bootstrap 3

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

========== Update ======

In response to a question, you can use this with multiple modals on the same page if you specify different data-targets, rename your modals IDs to match and update the IDs of the form input fields, and finally update your JS to match these new IDs:
see http://jsfiddle.net/panchroma/owtqhpzr/5/

HTML

...
<button ... data-target="#myModal1"> ... </button> 
... 
<!-- Modal 1 -->
<div class="modal fade" id="myModal1" ...>
... 

<div class="modal-body"> <textarea id="textareaID1" ...></textarea></div>

JS

$('#myModal1').on('shown.bs.modal', function() {
  $('#textareaID1').focus();
})
Community
  • 1
  • 1
David Taiaroa
  • 25,157
  • 7
  • 62
  • 50
  • This gives maximum callstack error when jquery validation fires!. Hence this is of no use to me. – Vandita Apr 03 '19 at 08:28
  • @Vandita, if you want to start a pen on codepen.io that illustrates the problem you describe I'd be happy to look at it for you. – David Taiaroa Apr 03 '19 at 22:53
89

I found the best way to do this, without jQuery.

<input value="" autofocus>

works perfectly.

This is a html5 attribute. Supported by all major browsers.
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/Input

tmarois
  • 2,424
  • 2
  • 31
  • 43
  • After spending a couple hours trying to get this work how it should (click or on handlers) I found only one method that works which is the html5 autofocus attribute: `` – lots0logs Jun 27 '14 at 10:38
  • 2
    Here is how you can do it on an MVC3 control: `@Html.TextBoxFor(m => m.UserName, new { @autofocus="" })` – Flea Apr 07 '15 at 14:48
  • 26
    It hasn't worked for me... after showing bootstrap modal the input loses the focus – Diego Cotini Dec 08 '15 at 22:34
  • I too see the input gain focus for a moment after the bootstrap modal appears when using autofocus. However, the input then loses focus. Had to implement the .on() handler. – raddevus Dec 16 '16 at 03:43
  • 9
    This works if you remove `tabdindex="-1"` from your modal, however it only works once. Closing and re-opening doesn't focus. – Memet Olsen May 03 '17 at 12:20
  • It will not work in dynamic modals, but the accepted answer works well – M.J.Ahmadi Apr 25 '21 at 08:59
  • 2
    In bootstrap modal documentation, this is not supported for modal but it can be used for other forms. Due to how HTML5 defines its semantics, the autofocus HTML attribute has no effect in Bootstrap modals. To achieve the same effect, use some custom JavaScript: $('#myModal').on('shown.bs.modal', function () { $('#myInput').trigger('focus') }) – Sabaoon Bedar Jun 02 '21 at 03:55
  • autofocus works, but not in Bootstrap Modals.. – Reichlich Aug 09 '22 at 15:42
68

The answer of David Taiaroa is correct, but doesn’t work because the time to "fade in" the modal doesn’t let you set focus on input. You need to create a delay:

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

})
Nate
  • 18,752
  • 8
  • 48
  • 54
Marcos Furquim
  • 990
  • 8
  • 12
  • 2
    You are the only right here. Your solution is the only one that works. I tried to set a smaller value for timeOut but didn't work. Seems modal "finishes loading" at 1000ms :( – Enrique Jun 19 '15 at 15:42
  • 3
    The correct is to use the shown.bs.modal event: http://getbootstrap.com/javascript/#modals-events – Akhorus Sep 07 '15 at 21:43
  • 3
    Instead of using setTimeout(), you can use delay() like following... $('#textareaID').delay(1000).focus().select(); – Tony May 19 '16 at 22:07
29

The usual code (below) does not work for me:

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

I found the solution:

$('body').on('shown.bs.modal', '#myModal', function () {
    $('input:visible:enabled:first', this).focus();
})
11

I got that bootstrap added the following info on their page:

Due to how HTML5 defines its semantics, the autofocus HTML attribute has no effect in Bootstrap modals. To achieve the same effect, use some custom JavaScript:

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

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

Amr Elgarhy
  • 66,568
  • 69
  • 184
  • 301
9

This is the simple code that will work for you best on all popups that has any input field with focusing it

$(".modal").on('shown.bs.modal', function () {
    $(this).find("input:visible:first").focus();
});
Junaid Anwar
  • 844
  • 1
  • 9
  • 22
4

I think the most correct answer, assuming the use of jQuery, is a consolidation of aspects of all the answers in this page, plus the use of the event that Bootstrap passes:

$(document).on('shown.bs.modal', function(e) {
  $('input:visible:enabled:first', e.target).focus();
});

It also would work changing $(document) to $('.modal') or to add a class to the modal that signals that this focus should occur, like $('.modal.focus-on-first-input')

  • If you also want it to ignore readonly textboxes, modify the line to read: $('input:visible:enabled:not([readonly]):first', e.target).focus(); – Douglas Timms May 16 '19 at 14:57
4

First step, you have to set your autofocus attribute on form input.

<input name="full_name" autofocus/>

And then you have to add declaration to set autofocus of your input after your modal is shown.
Try this code :

$(document).on('ready', function(){
    // Set modal form input to autofocus when autofocus attribute is set
    $('.modal').on('shown.bs.modal', function () {
        $(this).find($.attr('autofocus')).focus();
    });
});
Fendi Septiawan
  • 453
  • 5
  • 6
3

try this code, it might work for you

$(this).find('input:text')[0].focus();
Jitesh Tukadiya
  • 1,269
  • 1
  • 11
  • 25
3

With Bootstrap 4: 1/ Remove "fade" class at <div class="modal fade"... 2/ Next (https://getbootstrap.com/docs/4.6/components/modal/)

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

If you are not remove "fade" class, the input will focus, but keyboard will not show in Safari on iOS

vlotus
  • 31
  • 1
2

if you're looking for a snippet that would work for all your modals, and search automatically for the 1st input text in the opened one, you should use this:

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

If your modal is loaded using ajax, use this instead:

$(document).on('shown.bs.modal', '.modal', function() {
    $(this).find('input:visible:first').focus();
});
Hassan ALAMI
  • 318
  • 1
  • 5
  • 18
1

Use the autofocus to search for the right form element:

$('.modal').on('shown.bs.modal', function() {
  $(this).find('[autofocus]').focus();
});
gal007
  • 6,911
  • 8
  • 47
  • 70
0

If you want to just auto focus any modal that was open you can put in you patterns or lib functions this snippet that will focus on the first input:

$('.modal').on('shown.bs.modal', function () {
  $(this).find('input:first').focus();
})
Gabriel Rodrigues
  • 510
  • 1
  • 8
  • 29
0

this is the most general solution

$('body').on('shown.bs.modal', '.modal', function () {
    $(this).find(":input:not(:button):visible:enabled:not([readonly]):first").focus();
});
  • works with modals added to DOM after page load
  • works with input, textarea, select and not with button
  • ommits hidden, disabled, readonly
  • works with faded modals, no need for setInterval
DanCZ
  • 187
  • 4
  • 10
0

Try to remove the tabIndex property of the modal, when your input/textbox is open. Set it back to what ever it was, when you close input/textbox. This would resolve the issue irrespective bootstrap version, and without compromising the user experience flow.

Pathik
  • 1
0

According to Bootstrap 4 docs:

Due to how HTML5 defines its semantics, the autofocus HTML attribute has no effect in Bootstrap modals. To achieve the same effect, use some custom JavaScript.

E.g:

$('#idOfMyModal').on('shown.bs.modal', function () {
    $('input:first').trigger('focus')
});

Link.

hatef
  • 5,491
  • 30
  • 43
  • 46
0

If you prefer to do it with pure javascript, this below will show the modal and also select the first input field:

export function showModalById(elementId) {
    var element = document.getElementById(elementId)

    var input = element.querySelector('input')
    element.addEventListener('shown.bs.modal', function (event) {
        input.focus()
    })

    var modal = bootstrap.Modal.getOrCreateInstance(element)
    modal.show()
}
cuasiJoe
  • 1,089
  • 10
  • 12
0

For Bootstrap 5, use addEventListener. This was the only way I could get it to work.

var myModal = document.getElementById('whiteModal')

myModal.addEventListener('shown.bs.modal', function () {
  document.getElementById('my-input').focus()
})

For more info, see getbootstrap.com/docs/5.0/components/modal/.

Jussi Hirvi
  • 565
  • 3
  • 6