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!

 

Comments

# re: OnKeyPress event - event.keyCode and event.which (validating for numarics)

Tuesday, August 18, 2009 12:37 PM by dtwow

Excellent!  Thanks so much.

# re: OnKeyPress event - event.keyCode and event.which (validating for numarics)

Monday, October 26, 2009 6:06 AM by VEEJay

Thanks worked fine

# re: OnKeyPress event - event.keyCode and event.which (validating for numarics)

Friday, December 18, 2009 6:57 AM by Mahdi

Thanks for this useful code..

I'll try it and i hope it work well..

# re: OnKeyPress event - event.keyCode and event.which (validating for numarics)

Saturday, December 26, 2009 6:53 AM by Karthick

Awesome code , thanks !