Reputation: 59
I am trying to restrict the user to enter only numbers in a text box
<input type="text" name="pQ[]" onkeypress=" return checkKeyVal(event)"/>
function checkKeyVal(ev)
{
if(ev.keyCode)
{
if(ev.keyCode<48 || ev.keyCode>57)
{
return false;
}
}
else
{
//For Firefox
if(ev.charCode<48 || ev.charCode>57)
{
return false;
}
}
}
I found out that keyCode does not work firefox so i added charCode. The problem now is that none of other keys like backspace, delete and arrow keys seem to be working in firefox
Upvotes: 1
Views: 10270
Reputation: 5585
The way you are constructing your logic is wrong. First let us look at the ascii codes for the following characters :
Back Space : 10
Delete : 127
Now for the arrow keys,it depends on what operating system and programming language you are using. There is no "ASCII code" per se. The operating system detects you hit an arrow key and triggers an event that programs can capture.
So a normal table for the signal for such keys will look like :
Normal Mode Num lock on
Make Break Make Break
Down arrow E0 50 E0 D0 E0 2A E0 50 E0 D0 E0 AA
Left arrow E0 4B E0 CB E0 2A E0 4B E0 CB E0 AA
Right arrow E0 4D E0 CD E0 2A E0 4D E0 CD E0 AA
Up arrow E0 48 E0 C8 E0 2A E0 48 E0 C8 E0 AA
However, for using javascript , normally we use :
left arrow: 37
up arrow: 38
right arrow: 39
down arrow: 40
Now these are event.keyCode in a browser, but not ASCII codes. Refer : this url.
Lets take a look at your logic,
if(ev.keyCode<48 || ev.keyCode>57)
{
return false;
}
so , backspace(10),left arrow(37),up arrow(38),right arrow(39),down arrow(40) are less than 48 and delete(127) is greater than 57.
Hence once these keys are pressed, they will return false and as such you will never see them in the UI for a key press. So what you need to do is change your condition , such that for those key presses , you get true.
Note :
You probably can make use of this code , which i normally use for java script purposes :
function isNumber(event){
var charCode = (event.which) ? event.which : event.keyCode;
if (charCode > 31 && (charCode < 48 || charCode > 57))
return false;
return true;
}
I have tested this puppy in IE 7, 8 , MF and chrome. Seems to work seamlessly every where. However, if there is some key press event that you want recorded explicitly for your self, then look up the event code in google and then block/un block it . Cheers !
Upvotes: 5
Reputation: 12974
The problem is that you are using the keypress
event, switch to keyup
or keydown
. Then keyCode
will start working for you in Firefox as well. Have a look at this Quirksmode article for some more information on browser behaviour with keystroke detection.
<input type="text" name="pQ[]" onkeyup="return checkKeyVal(event)"/>
Upvotes: 0