views:

872

answers:

2

How can I prevent users from using the backspace or delete keys in a textbox using JavaScript?

I have a text box in my web form. I want to use JavaScript on keypress of the textbox to disable the delete and backspace keys.

Can anyone help?

+2  A: 

Here's a bit of code to block the certain key press events - or something along those lines (haven't tested the code).

function isValidKey(e)
{
    var charCode = e.keyCode || e.which;
    if (charCode == 8 || charCode == 46)
        return false;

    return true;
}

<input id="tb_box" onkeydown="return isValidKey(event)" type="text" />
David Liddle
Is it working or am I doing something wrong ? Only backspace is working on FireFox but not IE.
Canavar
IE does not fire the keypress event for some non-character keys (e.g. delete, end, enter, escape, fkeys, etc.).
rahul
Its not working in FF 3.5 and IE 7.
rahul
Replace onkeypress with onkeydown.
rahul
I tend to shorten it to: var charCode = e.keyCode || e.which;
Keith
+10  A: 

Why are you letting people edit the contents of the text box but restricting them from being able to use basic editing keys? This sounds like you are creating a major usability issue - what if the user makes a typo?

I'd recommend either setting the readonly flag (if you don't want users to edit the value) or disabled flag (if you don't even want it submitted)

scunliffe
+1 for mentioning usability issue.
rahul
Seconded. Always avoid surprising users with functionality that they don't expect.
Keith