Javascript blocks the browser back event to prevent accidental operation to clear the form

  • 2020-03-29 23:58:02
  • OfStack

Because the customer is mostly do not understand the computer big rookie. So the operation is more error, sometimes did not select the text box, and then accidentally press the backspace, just hard to fill the form on the back of nothing. Looked up a lot of information on the Internet, and then integrated it. Share it with everyone. I also hope yogurt sister will check out my first tech blog. Hehe (don't mind my mentioning you.) . No more nonsense. On the source code.
//Handling keyboard events disables Backspace passwords or single - or multi-line text fields
function banBackSpace(e){ 
var ev = e || window.event;//Get the event object
var obj = || ev.srcElement;//Get the event source

var t = obj.type || obj.getAttribute('type');//Gets the event source type

//Gets the type of event used as a judgment condition
var vReadOnly = obj.getAttribute('readonly'); 
var vEnabled = obj.getAttribute('enabled'); 
//Handle null value cases
vReadOnly = (vReadOnly == null) ? false : true; 
vEnabled = (vEnabled == null) ? true : vEnabled; 

//When the Backspace key is struck, the event source type is password or single-line, multi-line text,
//And if the readonly property is true or the enabled property is false, the backspace key is disabled
var flag1=(ev.keyCode == 8 && (t=="password" || t=="text" || t=="textarea") 
&& (vReadOnly || vEnabled!=true))?true:false; 

//When the Backspace key is struck, the Backspace key is invalidated if the event source type is not password or if it is single-line, multi-line text
var flag2=(ev.keyCode == 8 && t != "password" && t != "text" && t != "textarea") 

// judge  
return false; 
return false; 

//Disable the back button for Firefox and Opera
//Disable the back button for IE and Chrome
window.history.forward(1);//Block the browser's built-in back button

The things to note are:

This code must be placed in the initialization method. Then use document.onkeypress=banBackSpace to call the method you wrote.
vReadOnly = (vReadOnly == null) ? false : true; For this code, the original colon was followed by vReadOnly<span style="font-family: Arial, Helvetica, sans-serif;"> This value , It was later found in my project that it returned empty , not null So it's changed to true . </span> 

The above method can be used to block the backspace event in non-text,password,textare, but it will not block the backspace event when the text box has a value. This is my first blog post and I hope you will appreciate it.

Related articles: