user611105
user611105

Reputation:

Javascript restricting to numbers, only works in Chrome

Using some very basic code such as (from another Stackoverflow question)

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

          return true;
       }
       //-->
    </SCRIPT>
  </HEAD>
  <BODY>
    <INPUT id="txtChar" onkeypress="return isNumberKey(event)" 
           type="text" name="txtChar">
  </BODY>
</HTML>

I've found that this code works beautifully when you are just inputting numbers. However, it seems to block copy/paste/select all functionally on Firefox, Safari, Opera (can't test IE since I'm running OSX 10.8.3) but it doesn't on Chrome. I can't seem to figure out why. Any ideas?

I've also tried the Jquery AlphaNum library

https://github.com/KevinSheedy/jquery.alphanum

But that also exhibits the same behavior.

Upvotes: 3

Views: 935

Answers (4)

KevSheedy
KevSheedy

Reputation: 3265

On Firefox for MacOS, you need to also check the e.metaKey attribute which corresponds to the cmd key.

This is now fixed in jquery.alphanum V1.0.9 and the issue you described is logged as Issue #9.

Upvotes: 0

Arpit
Arpit

Reputation: 12797

To allow copy paste:

function isNumberKey(evt)
   {
      var charCode = (evt.which) ? evt.which : event.keyCode;
      if (charCode != 46 && charCode > 31 
        && (charCode < 48 || charCode > 57)) && !evt.ctrlKey  //ctrlKey returns boolean weather ctrl is pressed or not.
         return false;

      return true;
   }

Upvotes: 1

KooiInc
KooiInc

Reputation: 122906

Try this function:

function isNumber(e) {
        e = e || event;
        return +(String.fromCharCode(e.charCode || e.keyCode)) 
                || !e.charCode && e.keyCode < 48;
}

JsFiddle

Upvotes: 0

rationalboss
rationalboss

Reputation: 5389

The cut, copy, paste, and select all commands will work if you select it from the context menu (i.e. right-clicking on the text box and selecting the appropriate command).

However, the reason why Ctrl+X, Ctrl+C, Ctrl+V, and Ctrl+A do not work is they are also key events which are blocked by your function. When you press a key and it isn't a number, your function returns false.

The following code (from your post) blocks the input:

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

The keyboard shortcuts (Ctrl+X/C/V/A) have charCodes that are not in these range. You need to whitelist these commands by using the evt.ctrlKey property.

Upvotes: 2

Related Questions