Search code examples
jqueryasciikeypressbackspace

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


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?


Solution

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