Raaky
Raaky

Reputation: 11

Javascript keycodes not working in firefox but works well in chrome

I'm just doing my form validation wherein which Phone number has to be only numbers! The code works well in chrome but not in firefox and IE. pls give me some solution

My code is as follows

function noLet(event) {
    if (event.keyCode == 46 || event.keyCode==8 || event.keyCode > 47 && event.keyCode <      58) {
        event.returnValue = true;
    } 
    else {
        event.returnValue = false;
    }
}

HTML:

 onkeypress="noLet(e)"><label id="mobph"></label><font 

size="1"><br>Max 10 numbers only allowed!</font> 

Upvotes: 1

Views: 6180

Answers (4)

Arsman Ahmad
Arsman Ahmad

Reputation: 2211

There's compatibility issue of browsers. Here is a solution which I found out in some RND. Hope so it'll help you somehow; Click Here

Upvotes: 0

generationalVision
generationalVision

Reputation: 91

May i suggest the following code to solve your problem. This is what i am doing. Tested and works like a charm in ie, chrome and firefox:

//return numbers and backspace(charCode == 8) only
function noLet(evt) {
    var charCode = (evt.which) ? evt.which : evt.keyCode;
    if (charCode >= 48 && charCode <= 57 || charCode == 8)
        return true;
    return false;

Upvotes: 2

jeremy
jeremy

Reputation: 10047

You can use the key/char code to detect whether the key pressed is a number or not a number. First you have to detect what the key/char code is cross browser (remember to use event.keypress as your event to further assure compatibility). Afterwards, you convert it from its decimal value to its character. Then you can parse it as an integer using parseInt() which will return NaN if the first value inside the function cannot be parsed as an int. And then prevent the default action if it is NaN.

var numbersOnly = function(e){
    var charCode = (typeof e.which === "number") ? e.which : e.keyCode,
        chr = String.fromCharCode(charCode);
    if(isNaN(parseInt(chr, 10))) e.preventDefault();
}

<input type="text" name="phoneNumber" onkeypress="numbersOnly(event);">

Upvotes: 1

Michael Lorton
Michael Lorton

Reputation: 44376

Because on Firefox, at least, it's charCode, not keyCode in the keypress handler, and "returnValue" is ignored (invoke preventDefault() to stop the insertion).

Upvotes: 0

Related Questions