Question

I have a price field and I want to accept just numbers (I don't like the default html5 inputs like input[number] etc.) So I wrote this:

<input type="text" name="price" placeholder="" onkeypress="validate(event)">

function validate(evt) {
    var theEvent = evt || window.event;
    var key = theEvent.keyCode || theEvent.which;
    key = String.fromCharCode( key );
    var code = theEvent.keyCode || theEvent.which;
    var regex = /[0-9]/;
        if( !regex.test(key) && code != 8/*backspace*/ && code != 37/*left*/ && code != 39/*right*/ && code != 13/*enter*/ && code != 46/*delet*/ && code != 9/*tab*/){
        theEvent.returnValue = false;
        if(theEvent.preventDefault) theEvent.preventDefault();
        };
};

As you see some characters like left and right arrow keys, tab etc are added for better navigation. It works perfect in Chrome. In Firefox some characters are added unintentionally. For example the key code of both left arrow key and % is the same! so now my price field is accepting % in Firefox! I also found a simple regexp code whit the same problem. How can I make Firefox to understand?!

Was it helpful?

Solution

Actually the keyCodes for % and left arrow key are not the same.

  • %
    • .charCode == 37
    • .keyCode == 0
    • .which == 37
  • left arrow
    • .charCode == 0
    • .keyCode == 37
    • .which == 0

You need to fix your program logic and not mush codes together via ... = theEvent.keyCode || theEvent.which.

(Raw) Keyboard handling is a mess anyway, until browsers start implementing .key and .char correctly and fully.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top