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.

$(document).ready(function(){
	$('form').on('keyup keypress', function(e) {
	  	var keyCode = e.keyCode || e.which;
	  	if (keyCode === 13 && e.target.nodeName!='TEXTAREA') { 
	  		e.preventDefault();
	  		var onenterkeyfunc = $(e.target).attr('data-onenterkey');
	  		if(onenterkeyfunc!='undefined'){
	  			var tmpFunc = new Function(onenterkeyfunc);
	  			tmpFunc();	
	  		}
	  		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