'Disable form submission via Enter key on only _some fields
I want to retain the conventional 'form submits when i press Enter' behavior because users are familiar with. But by reflex, they often hit enter when they finish with a text input box - but before they are actually done with the complete form.
I'd like to hijack the Enter key only when then focus is on a certain class of input.
Looking Related Questions this looks like what I'm looking for:
if (document.addEventListener) {
document.getElementById('strip').addEventListener('keypress',HandleKeyPress,false);
} else {
document.getElementById('strip').onkeypress = HandleKeyPress;
}
but the if (document.addEventListener) { part is unfamiliar to me.
Solution 1:[1]
<input type="text" onkeydown="return (event.keyCode!=13);" />
Solution 2:[2]
Just add following code in <Head> Tag in your HTML Code.
It will Form submission on Enter Key For all fields on form
<script type="text/javascript">
function stopEnterKey(evt) {
var evt = (evt) ? evt : ((event) ? event : null);
var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
if ((evt.keyCode == 13) && (node.type == "text")) { return false; }
}
document.onkeypress = stopEnterKey;
</script>
Solution 3:[3]
To allow enter only on a specific class (in this example, 'enterSubmit'):
jQuery(document).ready(function(){
jQuery('input').keypress(function(event){
var enterOkClass = jQuery(this).attr('class');
if (event.which == 13 && enterOkClass != 'enterSubmit') {
event.preventDefault();
return false;
}
});
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | stackuser |
| Solution 2 | Kailas Mane |
| Solution 3 | Silas Palmer |
