elreeda
elreeda

Reputation: 4597

autofocus on input in bootstrap modal

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

Upvotes: 3

Views: 2987

Answers (3)

Obaidul Haque
Obaidul Haque

Reputation: 950

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>

Upvotes: 0

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

Upvotes: 2

tektiv
tektiv

Reputation: 14187

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

Upvotes: 3

Related Questions