[RESOLVED] Form focus placement in code differences
Greetings,
Problem: I would like to understand why javascript works in some locations but not in others.
Here is my xhtml code for a form that correctly sets focus on the first field - username.
Code:
<form id="loginform" action="loginresults.cfm" method="post">
<!--- Accept login credentials and call loginresults.cfm --->
<fieldset id="loginfieldset">
<label class="loginlabel" for="username" >Username: </label>
<input class="loginfield" id="username" type="text" name="UserName" value="" size="8" />
<label class="loginlabel" for="password">Password: </label>
<input class="loginfield" id="password" type="password" name="Password" value="" size="8" />
<input class="loginfield" id="submit" type="submit" name="B1" value="Login" alt="Login to the database" title="Login to the database"/>
</fieldset>
</form>
<!--- set focus on the first input field --->
<script type="text/javascript">
document.forms[0].username.focus()
</script>
But when I move the script code above the form tag, there is no field with focus.
Also, when I put a function with more generic focus code in the body tag onload, there is no field with focus. This used to work until I upgraded the site to XHTML 1.0 strict with CSS and accessibility.
Code:
<head>
<script type="text/javascript">
<!--- Set focus on the first form field --->
function setfocus() {
if (document.forms.length > 0) {
document.forms[0].elements[0].focus();
return true;
}
}
</script>
</head>
<body onload="setfocus()" >
This is a workable solution, I just want to understand why it works this way and not the others.
Bookmarks