13

Anyone know how can I disable backspace and delete key with Javascript in IE? This is my code below, but seems it's not work for IE but fine for Mozilla.

onkeydown="return isNumberKey(event,this)"

function isNumberKey(evt, obj)
{

    var charCode = (evt.which) ? evt.which : evt.keyCode
    if (charCode == 8 || charCode == 46) return false;

    return true;
}
Jin Yong
  • 42,698
  • 72
  • 141
  • 187

4 Answers4

13

This event handler works in all the major browsers.

function onkeyup(e) {
    var code;
    if (!e) var e = window.event; // some browsers don't pass e, so get it from the window
    if (e.keyCode) code = e.keyCode; // some browsers use e.keyCode
    else if (e.which) code = e.which;  // others use e.which

    if (code == 8 || code == 46)
        return false;
}

You can attach the event to this function like:

<input onkeyup="return onkeyup()" />
Joel
  • 19,175
  • 2
  • 63
  • 83
5

update based on @JoeCoders comment and the 'outdatedness' of my answer, I revised it.

document.querySelector([text input element]).onkeydown = checkKey;
function checkKey(e) {
    e = e || event;
    return !([8, 46].indexOf(e.which || e.keyCode || e.charCode) > -1);
}

See also this jsFiddle

Community
  • 1
  • 1
KooiInc
  • 119,216
  • 31
  • 141
  • 177
  • hmm, I'm pretty sure I've used that event attachment in all the big browsers (ie, ff, safari, chrome, opera). – Joel Mar 23 '09 at 14:07
  • I tried this code in jsFiddle (http://jsfiddle.net/x9tnxqLt/2/) and I can't get it to work in IE11, Firefox 35, or Chrome 40. It intercepts the keyup event and gets the code, but even when false is returned the browser still deletes characters from the input when backspace or delete are pressed. Joel Potter's code doesn't work either. – EricP Feb 05 '15 at 22:03
  • Rather an old answer: the jsfiddle @ http://jsfiddle.net/KooiInc/9r6bvaLd/ may work better – KooiInc Feb 07 '15 at 08:27
3

This code cancels backspace action.

window.onkeydown = function (event) {

    if (event.which == 8) { 

         event.preventDefault();   // turn off browser transition to the previous page 

                 // put here code you need 

        }; 

};      
2
$(document).keydown(function(e) {
    if (e.keyCode === 8) {
        var element = e.target.nodeName.toLowerCase();
        if ((element != 'input' && element != 'textarea') || $(e.target).attr("readonly")) {
            return false;
        }
    }
}); 
Paresh Vaniya
  • 41
  • 1
  • 8