How To Disable The Enter Key Using JQuery



TODO:

Have you ever wanted to disable the enter key for your entire form, including "modal" edit popup windows for the Telerik RadGrid?  If so, put this code in the document.ready function, and the Enter key will no longer submit your form data.

 

SOLUTION:

$(document).ready(function() {
        //disable the enter key, it causes too many issues....
        //Bind this keypress function to all of the input tags
        $('input').live('keypress', (function (evt) {
             //Deterime where our character code is coming from within the event
             var charCode = evt.charCode || evt.keyCode;
             if (charCode == 13) { //Enter key's keycode
                  return false;
             }
        }));

        //OR USE THE ONE BELOW.  ONE ABOVE WORKED BEST FOR ME
    function checkKeyPress(e) {
        if (e.keyCode == 13) {

            if (!e) var e = window.event;

            e.cancelBubble = true;
            e.returnValue = false;

            if (e.stopPropagation) {
                e.stopPropagation();
                e.preventDefault();
            }
        }
    }
    $("input").keydown(checkKeyPress);
})‚Äč

 

NOTES:

Method 1 worked for me, but I have seen method 2 used before also.