Prevent save on ENTER, but allow ENTER to call other functions

You can prevent the form from submitting, but still specify functions to execute when a user hits ENTER within a specific field or object.
JavaScript • JQuery

First, have this function called when the DOM is ready. The code below will allow ENTER keys on text areas, and look for the 'data-onenterkey' attribute value. If a function name was provided in the attribute, it will be executed.

	$('form').on('keyup keypress', function(e) {
	  	var keyCode = e.keyCode || e.which;
	  	if (keyCode === 13 &&!='TEXTAREA') { 
	  		var onenterkeyfunc = $('data-onenterkey');
	  			var tmpFunc = new Function(onenterkeyfunc);
	  		return false;

Create the custom function you want to call when the user hits the ENTER key on the specific input field

function myCustomFunction(){
     //do something

Sample usage

<input type="text" data-onenterkey="myCustomFunction()" value=""/>

Written by fbrefere001

Posted by fbrefere001 on Sunday July 21, 2019