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

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

I’ve seen a couple of questions in regards to bootstrap modals, but none exactly like this, so I’ll go ahead.
I have a modal that I call onclick like so…

This works fine, but when I show the modal I want to focus on the first input element… In may case the first input element has an id of #photo_name.
So I tried

But this was to no avail. Lastly, I tried binding to the ‘show’ event but even so, the input won’t focus. Lastly just for testing, as I had a suspiscion this is about the js loading order, I put in a setTimeout just to see if I delay a second, will the focus work, and yes, it works! But this method is obviously crap. Is there some way to have the same effect as below without using a setTimeout?
$(“#modal-content”).on(‘show’, function(event){
}, 0500);

Related:  get an element's id


Solution 1:

Try this

Here is the old DEMO:

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

$(document).ready(function() {
    $('#modal-content').on('shown', function() {

Starting bootstrap 3 need to use event:

$('#modal-content').on('', function() {

Solution 2:

Just wanted to say that Bootstrap 3 handles this a bit differently. The event name is “”.

$('#themodal').on('', function () {

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

.modal('show').on('', function ()

Solution 3:

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

  $('.modal').on('shown', function() {

Solution 4:

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('', function () {
    }, 100);

Probably it´s something about the animation!

Solution 5:

I had problem to catch “” event.. And this is my solution which works perfect..

Instead simple on():

$('#modal').on '', ->

Use on() with delegated element:

$('body').on '', '#modal', ->

Solution 6:

Seems it is because modal animation is enabled (fade in class of the dialog), after calling .modal('show'), the dialog is not immediately visible, so it can’t get focus at this time.

Related:  jQuery.when - Callback for when ALL Deferreds are no longer 'unresolved' (either resolved or rejected)?

I can think of two ways to solve this problem:

  1. Remove fade from class, so the dialog is immediately visible after calling .modal('show'). You can see for demo. (Sorry @keyur, I mistakenly edited and saved as new version of your example)
  2. Call focus() in shown event like what @keyur wrote.