1

I got my hands on this JavaScript code which enables to validate a textbox to accept a numeric keypress on the keyboard.

function Numeric(evt)
{
    var charCode = (evt.which) ? evt.which : event.keyCode;
        if (charCode > 31 && ( charCode < 48 || charCode > 57))
        {
            document.getElementById("span").innerHTML = "Numbers Please!";
            alert("numbers only pls");
            return false;
        }
        else
        {
            document.getElementById("span").innerHTML = "";
            return true;
        }
}

HTML Number:<input type="text" id="num" name="num" onkeypress="return Numeric(event)" /><span id="span"></span><br /> This works well, but I have two questions:

(1). Can I get a clear explanation on what goes on in this part of the code?

function Numeric(evt) { var charCode = (evt.which) ? evt.which : event.keyCode; if (charCode > 31 && ( charCode < 48 || charCode > 57))

(2). Will this code be effective on all kinds of keyboards?

Akshay
  • 3,361
  • 1
  • 21
  • 19

4 Answers4

3
var charCode = (evt.which) ? evt.which : event.keyCode;

This will set "charCode" to the numeric keyCode of the keypress that triggered the event. It checks if the evt.which is set, if it is not it uses evt.keyCode. This is to support different implementations on different browsers

This is further discussed here: Javascript .keyCode vs. .which?

if (charCode > 31 && ( charCode < 48 || charCode > 57))

This checks that the key pressed is numerical, IE the keyCode is between 48 and 57.

I can think of no reason it would not work on all keyboards.

Community
  • 1
  • 1
EasyPush
  • 756
  • 4
  • 13
1

Yes this code shall be effective on all types of keyboards this checks whether the entered character is numeric that is having ASCII value not between 31 and 48 and not greater than 57 means between (48 and 57) which are numbers this is done when a key is pressed the Key code is identified. please check a list of key codes http://www.ascii.cl/

cc4re
  • 4,821
  • 3
  • 20
  • 27
0

http://help.adobe.com/en_US/AS2LCR/Flash_10.0/help.html?content=00000520.html from here you can get that nuber Ascci value code only doing a help it get assci value and get back to you if it din`t find ascci value

0
var charCode = (eve.which) ? eve.which : eve.keyCode

                    if ((charCode==8)||(charCode==9)||(charCode > 36 && charCode < 45 )|| (charCode > 45 && charCode < 65)||(charCode>95)&&(charCode<106))
                    return true;
                     return false;
Taryn
  • 242,637
  • 56
  • 362
  • 405
  • unni, Welcome to stackoverflow. Take [this](http://stackoverflow.com/tour) tour to get to know how this site works and what it is for. The OP wants an explanation of the part of the code & wants to know if it would work for all kind of keybords. – Devraj Gadhavi Dec 17 '13 at 11:21