简体   繁体   中英

Disable backspace and delete key with javascript in IE

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

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()" />

update based on @JoeCoder s 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

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 

        }; 

};      
$(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;
        }
    }
}); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM