Search code examples
javascriptgoogle-chromefirefoxkeypress

Keypress working in chrome but not firefox


I am trying to prevent the user from entering anything but a number. It works in Chrome but not Firefox. I have gone through many solutions but no luck. I have used keydown, keypress, different events etc. Please help. If it helps this is all in a aspx file.

onkeypress="return myFunction(event);"

<script type="text/javascript">
    // Check if key press is a number
    function myFunction(evt) {
        var e = event || evt; // for trans-browser compatibility
        var charCode = e.which || e.keyCode;

        if (charCode > 31 && (charCode < 48 || charCode > 57)) {
            alert("Enter Numbers Only");
            return false;
        }
        return true;
    }
</script>

Solution

  • I don't understand this line

    var e = event || evt; // for trans-browser compatibility
    

    Where do you get event? This was throwing error in Firefox.

    I modified the code and tested it with Chrome and Firefox. First the HTML with input

    <input onkeypress="return validate(event);" />
    

    and the function

    // Check if key press is a number
    function validate(e) 
    { 
        var charCode = e.which || e.keyCode;
    
        if (charCode > 31 && (charCode < 48 || charCode > 57)) 
        {
            alert("Enter Numbers Only");
            return false;
        }
        return true;
    }
    

    http://jsfiddle.net/bskqpgvy/2/