Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
103
rated 0 times [  104] [ 1]  / answers: 1 / hits: 32177  / 11 Years ago, tue, november 5, 2013, 12:00:00

I'm using the commonly used Javascript function to allow only numbers to be inputted into a text field:



function isNumberKey(evt)
{
var charCode = (evt.which) ? evt.which : event.keyCode;
if (charCode != 46 && charCode > 31
&& (charCode < 48 || charCode > 57))
return false;

return true;
}


I call this onkeypress and it prevents anything but numbers to display. I'm trying to alter it so it will allow me to also put dashes (-) into the text field. The dash keycode is 189 so I tried this:



function isNumberKey(evt)
{
var charCode = (evt.which) ? evt.which : event.keyCode;
if (charCode != 46 && charCode != 189 && charCode > 31
&& (charCode < 48 || charCode > 57))
return false;

return true;
}


Thinking that the conditional statement would then accept the dash character but that didn't seem to work. Any ideas on why this would be? Thanks for your help!


More From » javascript

 Answers
6

If you're using the keypress event you need to use the character code 45 for dash/hyphen.



If you're using the keydown/keyup events then you need to use 109 and 189 to cover the minus key in the numeric keypad and the one (usually) located above the P key.



if (charCode != 46 && charCode != 45 && charCode > 31
&& (charCode < 48 || charCode > 57))
return false;


Demo: http://jsfiddle.net/J6B7U/



If you have doubts about which keycode is which a console.log(charCode); in your function will help you debug.



(Note also that trapping a key event is not enough to prevent invalid data being entered, because the user may change the field using the browser's edit menu or drag'n'drop.)


[#74503] Monday, November 4, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
annaw

Total Points: 18
Total Questions: 91
Total Answers: 98

Location: Guam
Member since Fri, Jun 18, 2021
3 Years ago
;