tags:

views:

38

answers:

4

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
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
+1  A: 

Did you try googling this?

document.getElementById("textboxId").focus();

Paul Creasey
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
@Rayne: You're right. Pay no attention to those saying otherwise.
George Edison
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
jQuery isn't the answer to **every** JavaScript question!
George Edison
i think its not a good advise for such a simple task.
meo
@meo: Exactly... import a ~60 kb library just so that you can set the focus to a text control. *No thanks!*
George Edison
@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
@George: And JQuery is 24Kb, not 60Kb.
TkTech
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
@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
@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
+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
Haha. I'm tempted to upvote solely for the awesome name!
George Edison
Interesting function name ;)
BradBrening
I'm not such a fast typer. So i have to use my imagination to get points :P
meo