Forum Moderators: open
<form name="myform2">
<input type="text" name="mytextfield2">
<input type="button" name="mybutton" value="Set Focus" OnClick="document.myform2.mytextfield2.focus();">
</form>
- John
[edited by: JAB_Creations at 6:53 am (utc) on May 19, 2007]
<form>
<input type="text" id="mytextfield2">
<input type="button" id="mybutton" value="Set Focus" OnClick="document.getElementById('mytextfield2').focus();">
</form>
Or anonymously
<form>
<input type="text">
<input type="button" id="mybutton" value="Set Focus" OnClick="this.form.elements[0].focus();">
</form>
That one's a little sloppy and hard to maintain though. :-)
<a name="totohere" id="gotohere" href="#andhereIam" OnClick="document.getElementById('mytextfield2').focus(); return false;">Go to my text field</a>
<a name="andhereIam" id="andhereIam"></a>
<input type="text" id="mytextfield2">
If Javascript is enabled, it will ignore href="#", if disabled, it will go the the portion of that page that contains the #.
You're really even better off defining a function in an external javascript for these objects so the JS is unobtrusive - see the discussion about attachClickEvents() in this thread [webmasterworld.com].
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Give Me Focus</title>
<script type="text/javascript">
function setFoci() {
if (document.getElementById) {
document.getElementById('focus_link').onclick = function() { document.getElementById('givemefocusplease').focus(); }
}
}
window.onload = function() { setFoci(); }
</script>
</head>
<body>
<a href="#focus_anchor" id="focus_link">give another element focus</a>
<br>
<p>add more breaks here to test</p>
<a id="focus_anchor"></a>
<input id="givemefocusplease" type="checkbox">
<br>
<p>add more breaks here to test</p>
</body>
</html>
- John
- John
- John