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

javascriptmodal-dialogtwitter-bootstrap

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…

$(".modal-link").click(function(event){
  $("#modal-content").modal('show');
});

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

   $(".modal-link").click(function(event){
     $("#modal-content").modal('show');
     $("input#photo_name").focus();
   });

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){
    window.setTimeout(function(){
      $(event.currentTarget).find('input#photo_name').first().focus()
    }, 0500);
  });

Best Answer

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