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

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.");
  }
}

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.

You need to use the onkeypress event.

<input 
  onkeypress="JavaScript:return key(event);"
  id="myTxt" />
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.