My page has a form that has a text field in it. I'd like to set the focus to that text field as soon as the page loads, so that users do not have to click it to start typing. How can I do this?
+2
A:
Use the focus() method on the object.
For example:
document.getElementById("something").focus();
...
<input type='text' id='something' />
George Edison
2010-05-09 21:26:53
Thanks. I actually tried that first, before posting, but it didn't appear to be working right. I must have not refreshed the page good enough. :P
Rayne
2010-05-09 21:36:20
+1
A:
Did you try googling this?
document.getElementById("textboxId").focus();
Paul Creasey
2010-05-09 21:28:02
I checked to make sure this question wasn't a duplicate. I'm fairly certain that that is the only prerequisite to asking a question. I feel that any question that hasn't been asked before is a decent contribution to this site as long as it isn't flat out stupid.
Rayne
2010-05-09 21:34:55
A:
I'd advise you to start using JQuery, which makes Javascript overall a much more enjoyable experience.
Say you had a search box on the page with the id searchfield - to focus it, $("#searchfield").focus()
TkTech
2010-05-09 21:29:02
@meo: Exactly... import a ~60 kb library just so that you can set the focus to a text control. *No thanks!*
George Edison
2010-05-09 21:33:36
@George: Its more than likely this isn't the ONLY thing in javascript he's going to be doing on this page. Looking towards the future, starting to use JQuery now will make his code a lot more maintainable.
TkTech
2010-05-09 21:34:46
I actually use JavaScript very very little for this page. I don't really do or care enough to pull in JQuery, but I still don't think this question deserves down votes. I would prefer that the non-jquery answer be included though.
Rayne
2010-05-09 21:38:12
@TkTech: you don't know in what context its used, maybe its a simple search page a la google :P i think if a question i tagged only with JavaScript the awnser should be just JavaScipt. No?
meo
2010-05-09 21:39:43
@TkTech: Sorry, 24kb is right - I got mixed up with something else. And you're right - if the OP is doing much else with JavaScript, he probably could use jQuery. However, that isn't stated in the question :)
George Edison
2010-05-09 21:40:50
+2
A:
you have to select your element first and then focus it by using focus() :P
function hokusfocus(e)
{
var fokus = document.getElementById(e);
fokus.focus();
}
onload = hokusfocus("yourId"); /* makes sure your document is loaded before the focus */
meo
2010-05-09 21:31:44