Disable Backspace key using java scriptIntroduction
Yesterday I was working on the online exam form. And I was told to disable the backspace button of the browser so that user can't go the previous page by pressing the backspace button of the KeyBoard.
After googling alot I found the useful code to disable the backspace button and default enter key from the key board. Although the user can go to the previous page by clicking on the backbutton image of the browser.
Code
<script type="text/javascript">
// Trap Backspace(8) and Enter(13) -
// Except bksp on text/textareas, enter on textarea/submit
if (typeof window.event != 'undefined') // IE
document.onkeydown = function() // IE
{
var t = event.srcElement.type;
var kc = event.keyCode;
return ((kc != 8 && kc != 13) || (t == 'text' && kc != 13) ||
(t == 'textarea') || (t == 'submit' && kc == 13))
}
else
document.onkeypress = function(e) // FireFox/Others
{
var t = e.target.type;
var kc = e.keyCode;
if ((kc != 8 && kc != 13) || (t == 'text' && kc != 13) ||
(t == 'textarea') || (t == 'submit' && kc == 13))
return true
else {
//alert('Sorry Backspace/Enter is not allowed here'); // Demo code
return false
}
}
</script>
When ever a user press the backspace key button, an event is generated. In the JS function above we can capture the event and do the action accordingly.
Happy Coding