An interesting problem - this happens, for example, in IE, but not in Chrome. Here is the solution I tested in Chrome and IE (it seems to work).
Extended version:
Script in page title:
<script> var buff; //Must have global scope var input = document.getElementById("testinput"); //Defined here to save cpu (instead of on every key press). function CheckPreBuff(e) { var ev = window.event ? event : e; //Get the event object for IE or FF var unicode = (typeof(ev.keyCode) != "undefined")? ev.keyCode : ev.charCode; if(unicode != 27) buff = input.value; //The 'escape' key has a unicode value of 27 else input.value = buff; //Only set the input contents when needed, so not to waste cpu. } </script>
Where "testinput" is the input we disabled. The following is the html test number:
<input id="testinput" onkeypress="CheckPreBuff();" onkeyup="CheckPreBuff();" type="text"/>
Note that both "onkeyup" and "onkeypress" were used - technically only "onkeyup", although using "onkeypress" prevents the text field from being filled out briefly while the escape key is pressed.
Manually minimized + error prevention + support for multiple inputs (if you prefer)
Script in title:
<script> var buff = []; function InitCPB(obj){if(typeof(obj)=="undefined")return;buff[0]=obj;buff[1]="";obj.onkeypress=CPB;obj.onkeyup=CPB;} function CPB(e){if(typeof((buff[0]))=="undefined")return;var ev=window.event?event:e;(((typeof(ev.keyCode)!="undefined")?ev.keyCode:ev.charCode)!=27)?buff[1]=(buff[0]).value:(buff[0]).value=buff[1];} </script>
testinput html tag (although the identifier is no longer needed):
<input onfocus="InitCPB(this);" type="text"/>
Both methods save a copy of what was inserted into the text boxes before pressing the next key, if the key pressed was "escape", unicode 27, then the previous text entry was put back into the text field (this is discriminatory, so the script does not add too much load to the browser each time you press a key).
The second version allows you to use multiple text inputs on the same page with the evacuation key disabled - only if they have the onFocus attribute, as described above (several elements will not interfere with each other). It also verifies that the objects passed to it are defined to prevent an accidental incorrect implementation giving IE a heart attack!
Hope this helps.
James
source share