0

This following code not allow user type new characters, but will allow delete characters:

$("#input_txt").keypress(function(event) {
event.preventDefault();
});

But I don't want to allow delete characters, How to do this ?

4b0
  • 21,981
  • 30
  • 95
  • 142

3 Answers3

1

You shouldn't use the keypress event, you should use keydown. It will work for you.

$("#input_txt").keydown(function (event) {
                event.preventDefault();
            });
Tien Nguyen Ngoc
  • 1,555
  • 1
  • 8
  • 17
0

You need to disable the input field altogether. Add disabled to the input tag:

<input (...) disabled>

Now it's greyed out and you can't edit it.

techfly
  • 1,826
  • 3
  • 25
  • 31
0

Preventing keypresses is a dirty and buggy way to prevent user inputs. Instead try disabling (as answered by @Aenadon) or making it readonly (as commented by @GuruprasadRao).

Disabling it also disables any interaction with the textbox, while making it readonly allows user to navigate through the text. In both the situations, the user will not be able to change anything in the textbox (yes, not even deleting).

You can do the above using jQuery like this:

$("#input_txt").prop("disabled", true); // Disable the text box
$("#input_txt").prop("readonly", true); // Make the text box read only
31piy
  • 23,323
  • 6
  • 47
  • 67