Disable enter submitting form with JavaScript

On a project I was working on I was asked to disable the enter key submitting the form.  Usually it would be better just to ensure that hitting enter performed the correct action but if you do want to disable this you can do so with JavaScript.

I created a JavaScript function called disableEnterSubmit which takes in the event as a parameter as shown below.

function disableEnterSubmit(e)
{
    if (e.keyCode)
       return (e.keyCode != 13); //IE
    else
        return (e.which != 13); //FireFox
}

The event has different properties for the code of the pressed key for Internet Explorer and FireFox. In Internet Explorer we use e.keyCode and for FireFox it’s e.which.  The function simply returns false if the key is enter (key code 13).

I then just need to set the onkeydown event in the body tag of my HTML to call the method.

<body onkeydown="return disableEnterSubmit(event)">
Posted on by Joe in JavaScript

Add a Comment