Set Focus on a Form

When my form is accessed I would like the cursor to be in the first input box on the form.  Does anyone know how to do this?  

Thanks.
Cindy
swartoutAsked:
Who is Participating?

[Webinar] Streamline your web hosting managementRegister Today

x
 
danrosenthalConnect With a Mentor Commented:
One important thing to note is the order in which things happen, generally a page is read by the browser from top to bottom. So if you put a command at the top of the page concerning form elements that have not been written yet it will trigger an error.  So either put this at the bottom of the page...

<SCRIPT language="JavaScript">
   document.myform.elements[0].focus();
</script>

Or as suggested by substand, put it in as an ONLOAD event in the BODY tag (which will get called only after the page is completely loaded...

<body onload="document.myform.elements[0].focus();">

However, I think it is generally a better practice to call a funtion rather than a direct javascript statement like so...

<body onload="startup();">

<SCRIPT language="JavaScript">
function startup(){
     document.myform.elements[0].focus();
}
</script>

(in this case the javascript function can be placed anywhere on the page as it will only get called after the page is fully loaded)



0
 
danrosenthalCommented:
you can do it like this...

document.myform.elements[0].focus();

0
 
danrosenthalCommented:
in the above example "myform" is the name of your form.

You can also set the focus to particular input by name like this...

document.myform.fieldname.focus();

0
Learn to develop an Android App

Want to increase your earning potential in 2018? Pad your resume with app building experience. Learn how with this hands-on course.

 
swartoutAuthor Commented:
what tag would I use with this?  Where would I put it on my form?
0
 
substandCommented:
you can either put it in the <body onload="document.myform.elements[0].focus();">

or you can just put a

<script>
document.myform.elements[0].focus();
</script>
0
 
substandCommented:
the script is supposed to go in the <head> section
0
 
Renante EnteraSenior PHP DeveloperCommented:
They all have the same idea with this mine...
Take this example...

<body onLoad="document.form1.user_name.focus()">
<form name='form1'>
  <input name="user_name" type="text">
  <input name="user_pass" type="password">
</form>
</body>

But if you also want that when you press enter key, it will focus to the next field. I have a javascript code for this...

I hope this example will help...
GOODLUCK!
0
 
swartoutAuthor Commented:
I placed the code at the bottom of the page and it works like a charm.  Thanks for your help.
0
All Courses

From novice to tech pro — start learning today.