RSS RSS feed
November 21, 2009
Hot Topics:

JavaScripts: Prevent a User from Entering Non-numeric Characters

  • January 31, 2002
  • By
  • Send Email »
This article was contributed by Bart T. McDonough.

Environment: IE 4.0 and above

Function Name: "CheckNumeric()"

This Javascript function prevents a user from being able to enter non-numeric data into a text field in an HTML form. When a user types data into a text field that uses this function, only numeric characters which are typed actually appear in the field. Any other characters are ignored and do not appear. It is a useful tool if you're looking for a simple way to ensure you have numeric data without having to write a validation routine.

To use this function, simply call it as an "onkeypress()" event handler in your <INPUT> tag in your HTML code. To see how this is done, view or download the source code below.

This function does not require any input parameters and does not output any return value.

function CheckNumeric()
{
   // Get ASCII value of key that user pressed
   var key = window.event.keyCode;

   // Was key that was pressed a numeric character (0-9)?
   if ( key > 47 && key < 58 )
      return; // if so, do nothing
   else
      window.event.returnValue = null; // otherwise, 
	                               // discard character
}

Downloads

Download demo project - .97 Kb
Download source - 1.11 Kb

History

Date Posted: January 31, 2002

# # #

1




Networking Solutions





Partners

  • Partner With Us














More for Developers

internet.commediabistro.comJusttechjobs.comGraphics.com

Search:

WebMediaBrands Corporate Info

Legal Notices, Licensing, Permissions, Privacy Policy.
Advertise | Newsletters | Shopping | E-mail Offers | Freelance Jobs