Disabling enter key for form

Chris Pinski picture Chris Pinski · Apr 12, 2011 · Viewed 109.3k times · Source

I have been trying to disable the Enter key on my form. The code that I have is shown below. For some reason the enter key is still triggering the submit. The code is in my head section and seems to be correct from other sources.

disableEnterKey: function disableEnterKey(e){
        var key;      
        if(window.event)
            key = window.event.keyCode; //IE
        else
            key = e.which; //firefox      

        return (key != 13);
    },

Answer

Steven Jiang picture Steven Jiang · Apr 12, 2011

if you use jQuery, its quite simple. Here you go

$(document).keypress(
  function(event){
    if (event.which == '13') {
      event.preventDefault();
    }
});