How to block keyboard keys in forms with javascript


A client asked me to block the ENTER key in a form I created for him. After some research, here is the piece of code you have to enter into the page, which will block the event:

<script type=”text/javascript”>
$(document).ready(function() {
document.onkeypress = stopRKey;
});
function stopRKey(evt) {
var evt = (evt) ? evt : ((event) ? event : null);
var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
if ((evt.keyCode == 13) && (node.type==”text”))  {return false;}
}
</script>
The 13 in the code above is the code for the ENTER key, replace that if you want to block an other keypress.
You can leave a response, or trackback from your own site.

Leave a Reply