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?
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?
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.