Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Javascript to validate numeric input, but allow tab,delete etc

Status
Not open for further replies.

jwhite68

IS-IT--Management
Jun 14, 2007
77
BG
I have tried to create a piece of javascript that will only allow entry of numbers; BUT also allow the user to use the DELETE,TAB, arrow keys, BACKSPACE keys so they can amend the entered numbers, or move to a number with arrow key to amend, or tab to next field in the form.

The following code works in IE, but in firefox the tab,delete,backspace and arrow keys dont work.
Anyone got a better script for this?

Code:
function OnlyNumbers(e)
{
var keynum
var keychar
var numcheck
 
if(window.event) // IE
{
keynum = e.keyCode
}
else if(e.which) // Netscape/Firefox/Opera
{
keynum = e.which
}
keychar = String.fromCharCode(keynum)
numcheck = /\d/
return numcheck.test(keychar)
//if( (keynum == 190 || keynum == 109 || keynum == 8) ||
//						(keynum >= 48 && keynum <= 57) || 
//						(keynum == 46) || 
//						(keynum >=37 && keynum <=40) || 
//						(keynum == 9) || 
//						(keynum >= 96 && keynum <= 105) ) { return true; }
//				else { return false; }
}

The last section, commented out, was something else I was trying, that didnt work.
 
For anyone interested, so far I have got this code to do the trick - although only tested on Firefox and IE 6.

Code:
function OnlyNumbers( e )
{
e = e || window.event;
ch = e.which || e.keyCode;
if( ch != null) {
if( (ch >= 48 && ch <= 57)
|| ch == 0 || ch == 8
|| ch == 13 || ch == 9   || ch == 46
||  (ch >= 37 && ch <= 40) 
|| ch == 109 || ch == 190 ) return true;
}
alert('Please enter a numeric value.');
return false;
}
 
Surely this would be easier to do on form validation rather than as the text field is being written to ?
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top