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
2 Answers
Reset to default 4Your 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
版权声明:本文标题:javascript - jQuery focus() on Bootstrap input field not working - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741645998a2390187.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论