Why is backspace allowed in my jQuery whether I filter it out or not?

207 views Asked by At

I've got this jQuery:

$(document).on("keypress", '[id*=Float]', function (e) { 
    //only allow 1..9 (48..57), '.' (46), and backspace (8)
    var k = e.which;
    if (k === 8 || k === 46) return;
    if (k < 48 || k > 57) { e.preventDefault(); }
});

...working on this HTML:

<input type="text" id="txtbxFloat">
</br>
<input type="text" id="txtbxHopeFloats">
</br>
<input type="text" id="txtbxFloatingFreeAsABird">

It can be fiddled with here

It does what the comments say/what I want. However, so does this:

$(document).on("keypress", '[id*=Float]', function (e) { 
    //only allow 1..9 (48..57), '.' (46), and backspace (8)
    var k = e.which;
    if (k === 46) return;
    if (k < 48 || k > 57) { e.preventDefault(); }
});

IOW, the "8" (backspace) is allowed in either case. Why? I guess it's not a problem for me at the moment, but what if I really wanted to prevent a backspace?

3

There are 3 answers

0
BReal14 On BEST ANSWER

If you really want to prevent backspace, you should unbind the default event and re-attach a 'new' version of it.

Try something like:

$(document).unbind('keydown').bind('keydown', function (event) {
    var doPrevent = false;
    if (event.keyCode === 8) {
        var d = event.srcElement || event.target;
        if ((d.tagName.toUpperCase() === 'INPUT' && (d.type.toUpperCase() === 'TEXT' || d.type.toUpperCase() === 'PASSWORD' || d.type.toUpperCase() === 'FILE')) || d.tagName.toUpperCase() === 'TEXTAREA') {
            doPrevent = d.readOnly || d.disabled;
        }
        else {
            doPrevent = true;
        }
    }

    if (doPrevent) {
        event.preventDefault();
    }
    // rest of code here
});
1
Ole Spaarmann On

I think the solution would be to use keydown instead of keypress.

The keyboard events occur in this order: keydown, keyup, keypress.

$(document).on("keydown", '[id*=Float]', function (e) { 
    //only allow 1..9 (48..57), '.' (46), and backspace (8)
    var k = e.which;
    if (k === 46) return;
    if (k < 48 || k > 57) { e.preventDefault(); }
});
4
Amit.rk3 On

I think keypress is not triggered when using backspace because keypress fires when actual character(any printing key) is being entered. Backspace doesn't enter any character. While keydown fires if any key is pressed. That's why keydown should work to prevent backspace.

This is what is mentioned in Jquery spec

The keypress event is sent to an element when the browser registers keyboard input. This is similar to the keydown event, except that modifier and non-printing keys such as Shift, Esc, and delete trigger keydown events but not keypress events.** Other differences between the two events may arise depending on platform and browser.