admin管理员组

文章数量:1296905

I want a search input field to automatically get focus on page load. So I tried the following approach:

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

This however does nothing at all. I thought it might conflict with some other code I have, so I did a simple test at a Bootstrap example page .html. In the Chrome console, I typed $('input:first').focus(); and this gave me <input class="span2" type="text" placeholder="Email"> as return value, but it didn't focus on the e-mail field too.

What am I doing wrong to simply focus on a certain input field when a page loaded?

I want a search input field to automatically get focus on page load. So I tried the following approach:

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

This however does nothing at all. I thought it might conflict with some other code I have, so I did a simple test at a Bootstrap example page http://twitter.github./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 return value, but it didn't focus on the e-mail field too.

What am I doing wrong to simply focus on a certain input field when a page loaded?

Share asked Nov 14, 2012 at 16:35 EsTeGeEsTeGe 3,0655 gold badges30 silver badges43 bronze badges 2
  • You can't focus from the console because it currently has focus (imagine trying to focus while another tab is active - it won't work). If you do setTimeout(function(){$('input').eq(0).focus();}, 1000); and quickly click back to focus the page again it will work. Can you post a link to the page you're having issues with or set up a fiddle? – Snuffleupagus Commented Nov 14, 2012 at 16:41
  • $(function(){$('#searchbox').focus();}); – A. Wolff Commented Nov 14, 2012 at 16:45
Add a ment  | 

2 Answers 2

Reset to default 4

Your initial code should work just fine, but you didn't add the second pair of brackets to call your anonymous function. If it's at the bottom of the page, the relevant part of the DOM will be ready by then, making the jQuery domready unnecessary.

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

Should work just fine

You probably need to wait until page has loaded. Try something like:

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

本文标签: javascriptjQuery focus() on Bootstrap input field not workingStack Overflow