SoFunction
Updated on 2025-04-09

How to disable the Backspace key in JavaScript

Today, I found that when using the readonly="readonly" attribute, the text box is set to read-only<input type="text" readonly="readonly"/>There is a strange problem: if the cursor enters the read-only text box and presses the Backspace key, it will jump to the previous page. The effect is like clicking the back button of the browser to return to the previous page. However, there is no such problem under Firefox and Google. In order to solve this problem, a following method was written. If the text box is read-only, thenDisable Backspace key
The code is as follows:

// Handle keyboard events. Except for Backspace passwords or single or multi-line text boxes, no Backspace. function banBackSpace(e){ 
  var ev = e || ;//Get event object  var obj =  || ;//Get the event source  var t =  || ('type');//Get the event source type  //Get the event type as a judgment condition  var vReadOnly = ('readonly');
  // Handle null value situation  vReadOnly = (vReadOnly == "") ? false : vReadOnly;
  //When the Backspace key is typing, the event source type is password or single-line or multi-line text.  // If the readonly property is true or the enabled property is false, the backspace key will be invalid  var flag1=( == 8 &amp;&amp; (t=="password" || t=="text" || t=="textarea") 
     &amp;&amp; vReadOnly=="readonly")?true:false;
  // When the Backspace key is typing, if the event source type is not a password or a single line or multiple lines of text, the backspace key will be invalid.  var flag2=( == 8 &amp;&amp; t != "password" &amp;&amp; t != "text" &amp;&amp; t != "textarea")
     ?true:false;  
  
  //judge  if(flag2){
   return false;
  }
  if(flag1){ 
   return false; 
  } 
 }

=function(){
 //The back key is prohibited and acts on Firefox and Opera =banBackSpace;
 //The back key is prohibited and acts on IE and Chrome =banBackSpace;
}

After adding this processing, the problem of "pressing the Backspace key in the read-only input box to fall back to the previous page" can be easily solved.