Disable backspace and delete key with javascript in IE

前端 未结 4 721
面向向阳花
面向向阳花 2020-12-15 23:34

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.

on         


        
相关标签:
4条回答
  • 2020-12-16 00:02

    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 
    
            }; 
    
    };      
    
    0 讨论(0)
  • 2020-12-16 00:04

    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()" />
    
    0 讨论(0)
  • 2020-12-16 00:06
    $(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;
            }
        }
    }); 
    
    0 讨论(0)
  • 2020-12-16 00:23

    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

    0 讨论(0)
提交回复
热议问题