2

I'm using bootstrap 3 to create a modal box. I want to have it autofocus on the input area. I tried with jQuery, but I don't know, what is the problem?

JavaScript:

$('#click').click(function () {
    $('input').focus()
});

Here is a demo on JSFiddle

Fred Gandt
  • 3,948
  • 2
  • 31
  • 39
elreeda
  • 4,357
  • 2
  • 17
  • 44

2 Answers2

2

This may be hard code but add a Timeout function to focus it.
The fact is the modal isn't here yet so the browser can't focus an element in it.

$('#click').click(function() {
  setTimeout(function(){
    $('input').focus() 
  },500);
});
tektiv
  • 13,480
  • 5
  • 59
  • 68
2

I've updated your JSFiddle. When using the bootstrap modal window there are a number of custom events you can use. one of those is shown.bs.modal wich runs after a modal is fully shown (and your input field is focusable). Remember that the event will be triggered on the modal, not on whatever opened the modal.

$('#myModal').on('shown.bs.modal', function () {
   $('input').focus();
})
Erik Inkapööl
  • 368
  • 2
  • 11