In a form, how do you assign a particular text field to have the cursor appearing there by default?
Lougraham
![]()
| SitePoint Sponsor |
In a form, how do you assign a particular text field to have the cursor appearing there by default?
Lougraham
![]()
LouiseG





Put the following code in the <head/> section of your HTML and replace field1 in the script with the field name in which you want to place the focus.PHP Code:<script type="text/javascript" language="JavaScript">
function toForm() {
document.form.field1.focus();
}
</script>
Andy![]()
Awestmoreland, I don't think that's right.
I just tried that and it didn't work (IE 5.2.2 Mac).
(Besides which, you forgot to mention to call the function to trigger the focus script)
There are two routes to doing this.
The first option is to give an id to the text field that you want focussed. (The id firstfield is used here as an example.)
<input type="text" id="firstfield">
Then, you can simply use the DOM to address the element called field and tell it to focus as soon as the page has finished loading.
<body onload="document.getElementById('firstfield').focus();">
Alternatively, you could wrap that up into a function and call it by its function name in the body tag instead (to keep the scripting separate from the markup).
function setFocus() {
document.getElementById('firstfield').focus();
}
...
<body onload="setFocus()">
---
The second option is based on the number of form elements on the page. It also uses the element id.
Javascript can address form elements by counting them and then performing a script on the first, second, third... element.
*** Javascript starts counting from 0, so the first form element will be number 0, the second will be number 1, etc...) ***
If the text field is the first form element (#0) on the page then you can address it like this.
document.forms[0].firstfield.focus()
You can wrap this into a function also as mentioned before or put it straight into the body and attaching it to an onload event.
Both these methods can be written to be more flexible and reusable.
Fwiw, you don't even need to attach it to the onload event (or any other event).
As long as the javascript command line is *after* the line of code containing the textfield, then it will still focus it.
For an example of this, just check the code at Google.co.uk or Hotmail.com. They both use javascript to set the focus on their forms.
Hope that helps![]()
New Plastic Arts: Visual Communication | DesignateOnline
Mate went to NY and all he got me was this lousy signature
Bookmarks