JQuery focus () in Bootstrap input box not working

I want the search input box to automatically focus on page loading. So I tried the following approach:

(function () { $('#searchbox').focus(); }) 

It does nothing at all. I thought this might conflict with some other code that I have, so I did a simple test on the Bootstrap sample page http://twitter.github.com/bootstrap/examples/hero.html . In the Chrome console, I typed $('input:first').focus(); and this gave me <input class="span2" type="text" placeholder="Email"> as the return value, but it also did not focus on the email field.

What am I doing wrong to just focus on a specific input field when the page loads?

+4
source share
2 answers

You probably need to wait until the page loads. Try something like:

 $(document).ready(function () {$('#searchbox').focus(); }); 
+2
source

Your source code should work fine, but you did not add a second pair of parentheses to call the anonymous function. If at the bottom of the page, the corresponding part of the DOM will be ready by then, making jQuery even more unnecessary.

;(function () { $('#searchbox').focus(); })();

Should work just fine

+4
source

Source: https://habr.com/ru/post/1446039/


All Articles