How do I have the cursor focus to a text field on page load?

Here I’m explaining how to focus cursor to a text field on page load. You can do this with several methods with a simple javascript code. For this, you have to put a name for your form and your text filed. See the sample form below.

<form name="myForm" method="post" action="">
  <label>
      <input type="text" name="username" />
  </label>
  <label>
      <input type="submit" name="Submit" value="Submit" />
  </label>
</form>

Now just look on the code. You can do this with a single line code within body onLoad.
<body onLoad="document.myForm.username.focus();">
You can call this code with a function like this:
<script>
  function curFocus(){
     document.myForm.username.focus();
  }
</script>
<body onLoad="curFocus();">

Another method is put the code inside the page after the form. See how is it.
<script type="text/javascript" language="JavaScript">
  var focusCtrl = document.forms["myForm"].elements["username"];
       if(focusCtrl) {
           focusCtrl.focus();
   }
</script>

Share with Friends
[Facebook] [Jamespot] [Reddit] [StumbleUpon] [Twitter] [Email]

26 thoughts on “How do I have the cursor focus to a text field on page load?”

  1. Pingback: blogbookmark.com
  2. Pingback: Blogsvine
  3. Pingback: linksmarker.com
  4. Pingback: PlugIM.com
  5. 1. Assigning to document.unload is poor citizenship. If anything else on your page requires similar handling, you will have to have your onload method do more than set the focus, and a lazy programmer might not even change its name from ‘curFocus’. Instead, use addEvent (IE) or addEventListener (Firefox, etc.)

    1.1. Instead of using conditional code to choose between addEvent and addEventListener, after you’ve learned to do that, consider using a JavaScript library such as Prototype or jQuery.

    2. Adding raw Javascript to your page is messy. Place it in a separate file, and invoke it with a script src=”…” element.

  6. Sorry for my bad english. Thank you so much for your good post. Your post helped me in my college assignment, If you can provide me more details please email me.

  7. Hi, you?re making some good bloging there!Keep up the hard work!I?ll folow your blog, you could also follow mine! http://www.bestpokernodepositbonus.blogspot.com mine it?s so no good as yours it just talks about Poker Bonus Without Having to make a Deposit!Congratulations for your blog , visit mine and leave your comment there I would apeciate it!

Leave a Reply

Your email address will not be published. Required fields are marked *