Search code examples
javascriptjquerymozilla

KeyCode is taking wrong in mozilla


My javascript code to disable decimals in textbox ix like this

$(document).ready(function() {
    $(".money-input").keypress(function (e) {
        // between 0 and 9
        if (e.which < 48 || e.which > 57) {
            alert(1);
            showAdvice(this, "Integer values only");
            return (false);  // stop processing
        }
    });

    function showAdvice(obj, msg) {
        $("#singleAdvice").stop(true, false).remove();  // remove any prev msg
        $('<span id="singleAdvice" class="advice">' + msg + '</span>').insertAfter(obj);
        $("#singleAdvice").delay(4000).fadeOut(1500);  // show for 4 seconds, then fade out
    }
});

This works perfect in Chrome. But when i go to Mozilla. Back space alos get in to that if case. So when I press back space nothing happens and error message is shown. Can anyone point out what I am doing wrong herE?


Solution

  • The keypress event does not fire for non-printable characters, like Esc, Ctrl, Shift, and in your case, backspace.

    Use keyup() instead:

    $(".money-input").keyup(function(e) {
        if (e.which < 48 || e.which > 57) {
            showAdvice(this, "Integer values only");
            return false;
        }
    });
    

    Example fiddle