3

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
  • 4,217
  • 2
  • 33
  • 41
elreeda
  • 4,525
  • 2
  • 18
  • 45

3 Answers3

3

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
  • 14,010
  • 5
  • 61
  • 70
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
  • 378
  • 2
  • 11
0

I am also use this code

<script>
    function setFocusOnModal(){
        $('#searchModal').on('shown.bs.modal', function () {
            $('#q').focus();
        });
    }
</script>

Where #searchModal is modal div ID and #q is input element ID

Use this code in button

<button type="button" onclick="setFocusOnModal()">Open Modal</button>
Obaidul Haque
  • 916
  • 11
  • 18