Submit Form With Enter Key Using jQuery

By default in most browsers, hitting the Enter key will trigger the browser to follow the the URL or button that currently has tab focus. Sometimes it seems as though the browser does whatever it wants after the user hits Enter because the focus isn’t readily apparent. In an interface with one or more forms, it is preferable to have the Enter key trigger the submission of the form so that the user isn’t forced to use his pointer to click the submit button. It’s also nice to include this feature to avoid data loss when the user inevitably hits Enter and the browser decides to go wherever it feels like it.

In this example, we add code that allows the user to submit a form with the enter key using jQuery.

Example HTML form:

<div id='form_1'>
  Field 1: <input type='text' name='field_1' id='field_1'>
  <p> </p>
  <button type='button' id='form_1_submit_button'>Submit</button>

jQuery Code:

In the following jQuery code, we have a self-executing anonymous function that binds a click event handler to #form_1_submit_button and an event handler for the Enter keypress inside #form_1. Whether the user specifically clicks the submit button or hits the Enter key anywhere inside the form, the ValidateForm() function is called.

<script src=""></script>
<script type="text/javascript">
  //submit form with enter key using jQuery
  $(function() {
    $("#form_1_submit_button").click(function() {

    $("#form_1").keypress(function(e) {
      if(e.which == 13) {

        return false;

Resolve jQuery and MooTools Conflict

jQuery and MooTools are great JavaScript libraries for introducing dynamic interactions to your web site or application. They both include capabilities for manipulating CSS and adding various effects and animations as well as pre-built Ajax functions. However, if you need to use both on the same page, then you’ll immediately have a conflict since they both use the same namespace by default. To avoid the conflict, jQuery includes the ability to modify its namespace using jQuery.noConflict(). If you call this method after loading the jQuery library, then all references to jQuery should use “jQuery” instead of “$.” This will allow MooTools to function using $. The particular issue I had was a conflict between jQuery, Thickbox and MooTools. Correcting this conflict required the additional step of changing all references to $ in the Thickbox library to “jQuery.” Thickbox includes some uses of $ that shouldn’t be replaced, so don’t perform a global find and replace.

<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">