Emanuel Malacarne
Emanuel Malacarne

Reputation: 45

onkeypress event in Firefox

I'm looking for a solution for a (as it seems) common problem.

I want JavaScript to check a specific format when entering data in a input-field.

This is what I've got:

HTML:

<input onkeypress=" return fieldFormat(event)">

JavaScript:

<script type="text/javascript">

    //Checks spelling in realtime, if JavaScript is enabled.
    function fieldFormat(event){
        var charCode = (window.event) ? window.event.keyCode : event.keyCode;
        var parts = event.target.value.split('.');
        if (charCode > 31 && (charCode != 46 &&(charCode < 48 || charCode > 57)) || (parts.length > 1 && charCode == 46))
            return false;
        return true;
    }

</script>

This works fine in Chrome and IE. But for some reason, Firefox gives me troubles ^^

Any hints?

Upvotes: 0

Views: 325

Answers (2)

Bartosz Janik
Bartosz Janik

Reputation: 51

Check this one - seems like it's common https://support.mozilla.org/pl/questions/998291

Upvotes: 0

laruiss
laruiss

Reputation: 3816

Some browsers use keyCode, others use which, so try this:

function fieldFormat(event){
    var e = event || window.event,
        charCode = e.keyCode || e.which,
        parts = e.target.value.split('.');
    if (charCode > 31 && (charCode != 46 &&(charCode < 48 || charCode > 57)) || (parts.length > 1 && charCode == 46))
        return false;
    return true;
}

Upvotes: 1

Related Questions