"jhoff" <jh***@elitepcrepair.comwrites:
I'm trying to use javascript to execute code when the enter key is
pressed in a text box.
If it's the only text box in the form, the simplest would be to put
your code in the onsubmit handler of the form.
<html>
<body onload="load()" onunload="GUnload()">
<form name=zipform>
<input type="text" name="zipcode" value="" size="5"
class="flat">
<input type="button" name="button" value="Click"
onClick="changezip(this.form.zipcode.value);">
</form>
</body>
<script type="text/javascript">
function checkCR(evt)
{
var evt = (evt) ? evt : ((event) ? event : null);
This line fails if "event" is not defined in the scope, i.e., as
a global variable. Instead, you can use:
var evt = evt || window.event;
(generally, "foo ? foo : bar" is equivalent to "foo || bar")
var node = (evt.target) ? evt.target : ((evt.srcElement) ?
evt.srcElement : null);
again:
var node = evt.target || evt.srcElement;
You can also consider doing something if there is no node detected
here.
if ((evt.keyCode == 13) && (node.type=="text") &&
(node.value.length==5))
are you trying to detect whether the node is the input field? In
that case, it's much easier to just check that:
if (evt.keyCode == 13 &&
node == document.forms['zipform'].elements['zipcode']) { ///...
{
changezip(this.form.zipcode.value);
Here you use "this" to refer to ... well, I don't know what you
expect it to refer to, but since this method is being called
as an event handler on the document, "this" refers to the document,
which most likely doesn't have a "form" property.
So, this fails, the code stops executing, and the keyevent is not
cancelled. Well, it's not cancelled anyway in this branch of the
code.
Do your browser give you any error messages?
}
else if ((evt.keyCode == 13) && (node.type=="text"))
{
return false;
}
}
document.onkeypress = checkCR;
Put the check on the input field where it is needed:
document.forms['zipform'].elements['zipcode'].onkeypress = checkCR;
I DO NOT want to reload the page ( I.E. post the contents ) when the
enter key is pressed. In the case i've created, pressing the "click"
button after entering a zipcode, executes the javascript function
"changezip", however pressing enter will reload the page, and tack the
"?zipcode=xxxxx" to the end of the url...
Submitting is the default action for pressing return on a text field.
--
Lasse Reichstein Nielsen -
lr*@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
'Faith without judgement merely degrades the spirit divine.'