Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
437 views
in Technique[技术] by (71.8m points)

javascript - Allow only numbers or decimal point in form field

I've limited the input field to only numbers through js but am not sure how to also allow decimals...

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

         return true;
      }

Thank you in advance!

Answer:

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

 return true;
 }

Adding the charCode 46 worked perfectly (keypress value). 190 and 110 did nothing.

Thanks for your help all!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Codes depend on which event you're listening to, an easy way to find what you want is by using the JavaScript Event KeyCode Test Page here with test input, e.g. for a full stop (the . left of right shift) you have

               onKeyDown    onKeyPress    onKeyUp
event.keyCode        190            46        190
event.charCode         0            46          0
event.which          190            46        190

and for the . on the numeric pad it is

               onKeyDown    onKeyPress    onKeyUp
event.keyCode        110            46        110
event.charCode         0            46          0
event.which          110            46        110

As you can see, it is most uniform to check with onKeyPress with charCode which is it's unicode number; String.fromCharCode(46); // ".".

There is a full list on the MDN page for KeyboardEvent where it is also stated

Note: Web developers shouldn't use keycode attribute of printable keys in keydown and keyup event handlers. As described above, keycode is not usable for checking character which will be inputted especially when Shift key or AltGr key is pressed. When web developers implement shortcut key handler, keypress event is better event for that purpose on Gecko at least. See Gecko Keypress Event for the detail.

You can observe the strange effects of using AltGr or Shift on keyCode with the key of choice in the test page I linked to as well.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...