tags:

views:

2829

answers:

2

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;
}
+3  A: 

Yes:

function onkeyup(e) {
    var code;
    if (!e) var e = window.event;
    if (e.keyCode) code = e.keyCode;
    else if (e.which) code = e.which;  

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

You'll need to attach the event to this function like:

<input onkeyup="return onkeyup()" />
Joel Potter
Typo. if(keycode needs to say if(code
Josh Stodola
+2  A: 

Joels code wouldn't work in nonIE browsers because the event doesn't get sent in all browsers and because the variable 'keycode' is not defined. Alternative:

function checkKey(e) {
    e = e || event;
    if (!e) {return true;}
    var code = e.keyCode || e.which || null;
    if (code) {
      return (code === 8 || code === 46) ? false : true;
    }
    return true;
}

<input onkeyup="return checkKey(event)" />
KooiInc
hmm, I'm pretty sure I've used that event attachment in all the big browsers (ie, ff, safari, chrome, opera).
Joel Potter