Search code examples
javascriptjqueryonkeyuponkeypress

Cancel Backspace and all key press when inside a textbox


I have following sample code at https://js.do/sun21170/254818

My goal is to prevent editing of text inside the textbox without using the readOnly or disabled attribute. In above demo code, I am canceling the keyup event when Backspace is pressed, but this is having no effect.

Question: Is it possible to cancel the Backspace key press using JavaScript or jquery when inside a text box without using readOnly or disabled attribute of textbox?

The code of my demo is also as pasted below.

function keyPressed(e) { 
  e.preventDefault();
}
       
function keyUp(e) {
  e.preventDefault();
}
#text1 {
  width:500px;
}
<input type="text" id="text1" onkeypress="keyPressed(event)"     
         onkeyup="keyUp(event)" value="This is some text that should not be editable"></input>


Solution

  • I change onkeypress="keyPressed(event)" to onkeydown="keyPressed(event)", it works.