Search code examples
javascriptfirefoxonkeypress

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?


Solution

  • 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;
    }