event object
i have an input element with a type of text.
I want to check that only numbers are entered in the element.
I also want to alert the user when they enter anything that's not a number.
HTML for the element below.
<input type="text" id="QTY" name="QTY" title="Qty" size="3" onkeypress="key(event)" />
I need help with the function below.
//pseudo code
function key(e)
{
if (e.???? != "a number")
{
alert("Invalid entry. Please enter a number.");
document.getElementById(QTY).value = "";
}
}
Thanks
sj
Sailor_Jerry
Junior Poster in Training
88 posts since Aug 2005
Reputation Points: 13
Solved Threads: 2
The two major browsers, in conjunction with a properly-declared doctype, have two different Event models.
I'm not sure that you want to handle every keystroke. A regular expression might be the better way to validate this.
In any case, something like this:
function key(e)
{
var keycode;
if (navigator.appName == "Microsoft Internet Explorer")
{ keycode = e.keyCode; }
else
{ keycode = e.which; }
if (isNaN(keycode))
{
alert("Please enter a number.");
}
}
tgreer
Made Her Cry
2,118 posts since Dec 2004
Reputation Points: 227
Solved Threads: 37
I admit this is just a hack to get around the real problem...
The problem is that IE and FF behave differently with the following case:
<?xml version="1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"/>
<title></title>
<script>
function test()
{
alert("onblur event from 2nd input box");
}
</script>
</head>
<BODY>
<INPUT TYPE=text NAME=txtFName VALUE="First Name" onclick=alert("onclick event from 1st input box")>
<INPUT TYPE=text NAME=txtLName VALUE="Last Name" onblur="test()">
</BODY>
</HTML>
If there is a way to get FF to fire off the onblur event before the onclick, then I would not need to do validation that handles every keystroke.
Sailor_Jerry
Junior Poster in Training
88 posts since Aug 2005
Reputation Points: 13
Solved Threads: 2
You need to use the onkeypress event.
[html]
[/html]
tgreer
Made Her Cry
2,118 posts since Dec 2004
Reputation Points: 227
Solved Threads: 37