Click to See Complete Forum and Search --> : Numbers only in Textfield - Question in code


olerag
11-07-2003, 08:18 AM
The following code is from a text that only permits numerics
to be entered. Here's the code...


function numeralsOnly(evt) {
evt = (evt) ? evt : event;
var charCode = (evt.charCode) ? evt.charCode : ((evt.keyCode) ? evt.keyCode : ((evt.which) ? evt.which : 0)));
if (charCode > 31 && (charCode < 48 || charCode > 57)) {
alert("Enter numerals only in this field.");
return false;
}
return true;
}


The code is fired with an "onkeypress" event on the form
object.

The problem I have is discerning the "jumbled" code in
the instantiation of the "charCode" variable. Could someone
please offer a nice interpretation how this variable is
obviously retaining what character is being pressed.

Another question. If I wanted to test to permit only the
first character in the string to be signed (permitting either a
"-" or "+" sign, how would this affect the code presented above?

Thanx for any/all assistance...

96turnerri
11-07-2003, 08:44 AM
bascially the charcode has to be

> 31 & < 48 or

> 31 & > 57 so basically >57

not permitted are

<32 and

>47 but less than <58

olerag
11-07-2003, 10:07 AM
Yep, I understand what is happening; my problem is trying
to discern the code that is capturing the key as provided when
the "var charCode" is initially instantiated.

As far as trying to capture other activities, I'll include my
current code and let others, if they like, chew it up and
possible offer better solutions/alternatives.


function numbersOnly(evt, val, bool) {
evt = (evt) ? evt : event;
var charCode = (evt.charCode) ? evt.charCode : ((evt.keyCode) ? evt.keyCode : ((evt.which) ? evt.which : 0));
if ( (charCode >= 48 && charCode <= 57) || charCode == 8 || charCode == 9 || charCode == 13) {
return(true);
else {
if (charCode == 45 && val.length == 0 && bool) {
return(true);
}
if (charCode == 46 && val.indexOf(\".\") == -1) {
return(true);
}
}
return(false);
}


The "bool" arg is a boolean that indicates if a "signed"
integer is permitted. I'm not crazy about the way it is currently
implemented as the field must be null otherwise the "neg"
is not permitted as the first char in the field.

Also, the backspace, tab, and return chars are permitted but
I'm not taking into account the "del" or cursor movement
keys. I believe "delete" must be ascii 16; are the four
cursor movement keys 17-20??