Search code examples
jqueryeventstextboxrestrict

Key Press Event not stopping backspace


I have a textbox where I need to prevent the user from manually entering anything into it. I wrote a keypress event handler in the following manner:

funcion Keypress(Event e) {
    e.preventDefault();
}

By using the above code, I was able to restrict the user to not enter any thing. The value in the textbox will be filled by some other event (a dropdown change).

After the value is filled in the textbox, if I use backspace , it still is working and deleting the data in the text box.

Can any one please suggest me to restrict any keypress on the textbox.


Solution

  • You can use the readonly attribute to do this, no JS required.

    <input type="text" name="foo" readonly="true" />
    

    This still allows you to set the value programmatically via javascript.

    Example fiddle