Assign the “Enter” key to simulate a button click in jQuery

JavaScript
// jQuery

What it does

Link the “Enter” key to act as a button click on your form, instead of forcing users to use the mouse.

The Code

$(document).ready(function(){
	// Store the input field as a variable
	// NOTE :: Change "inputID" to your input field's ID
	var input = document.getElementById("inputID");

	// If the input field exists
	if ($(input).length > 0) {
		// Add a listener for the release of a key
		input.addEventListener("keyup", function(event) {
		  // Prevent the default action, just in case
		  event.preventDefault();
		  // When the "Enter" key is released
		  // NOTE :: The number 13 is the keyboard's "Enter" key
		  if (event.keyCode === 13) {
		    // Simulate a click on the button
			  // NOTE :: Change "buttonID" to your button's ID
		    document.getElementById("buttonID").click(); 
		  }
		});
	}
});

How To Use It

Paste this snippet into a JavaScript file that is loaded by your page, or you can put it between <script> </script> tags in the footer.

jQuery is required.

Menu