OnKeyPress event - event.keyCode and event.which (validating for numarics)
I
am trying to validate textbox for numeric entry, while I added this
code to accomplish in page_load event:
textbox.Attributes.Add("onkeypress",
"return
(window.event.keyCode == 45 || window.event.keyCode == 13 ||
window.event.keyCode == 8 || window.event.keyCode == 9 ||
window.event.keyCode == 189 || window.event.keyCode == 109 ||
(window.event.keyCode >= 48 && window.event.keyCode <=
58) )");
It
worked fine in IE7 and IE8, but it didnt work for FF though. A bit
googling gave me conclusion that FF doest recognize
window.event.keyCode.
Basically
Firefox supports the which property instead of the keyCode property
IE does. By checking which (window.event.which)
of
them exists with an if statement we can reliably get the key that was
pressed.
I
replaced above code with:
textBox.Attributes.Add("onkeypress",
"var
key; if(window.event){ key = event.keyCode;}else if(event.which){ key
= event.which;} return (key == 45 || key == 13 || key == 8 || key ==
9 || key == 189 || (key >= 48 && key <= 58) )");
it
worked for both IE and FF. Hope
it would help someone in same need!