How do you prevent an ENTER key press from submitting a form in a web-based application?
[revision 2012, no inline handler, preserve textarea enter handling]
function checkEnter(e){
e = e || event;
var txtArea = /textarea/i.test((e.target || e.srcElement).tagName);
return txtArea || (e.keyCode || e.which || e.charCode || 0) !== 13;
}
Now you can define a keypress handler on the form:
<form [...] onkeypress="return checkEnter(event)">
document.querySelector('form').onkeypress = checkEnter;
Here is a jQuery handler that can be used to stop enter submits, and also stop backspace key -> back. The (keyCode: selectorString) pairs in the "keyStop" object are used to match nodes that shouldn't fire their default action.
Remember that the web should be an accessible place, and this is breaking keyboard users' expectations. That said, in my case the web application I am working on doesn't like the back button anyway, so disabling its key shortcut is OK. The "should enter -> submit" discussion is important, but not related to the actual question asked.
Here is the code, up to you to think about accessibility and why you would actually want to do this!
$(function(){
var keyStop = {
8: ":not(input:text, textarea, input:file, input:password)", // stop backspace = back
13: "input:text, input:password", // stop enter = submit
end: null
};
$(document).bind("keydown", function(event){
var selector = keyStop[event.which];
if(selector !== undefined && $(event.target).is(selector)) {
event.preventDefault(); //stop event
}
return true;
});
});
Simply return false from the onsubmit handler
<form onsubmit="return false;">
or if you want a handler in the middle
<script>
var submitHandler = function() {
// do stuff
return false;
}
</script>
<form onsubmit="return submitHandler()">
//Turn off submit on "Enter" key
$("form").bind("keypress", function (e) {
if (e.keyCode == 13) {
$("#btnSearch").attr('value');
//add more buttons here
return false;
}
});
You will have to call this function whic will just cancel the default submit behaviour of the form. You can attach it to any input field or event.
function doNothing() {
var keyCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
if( keyCode == 13 ) {
if(!e) var e = window.event;
e.cancelBubble = true;
e.returnValue = false;
if (e.stopPropagation) {
e.stopPropagation();
e.preventDefault();
}
}
The ENTER key merely activates the form's default submit button, which will be the first
<input type="submit" />
the browser finds within the form.
Therefore don't have a submit button, but something like
<input type="button" value="Submit" onclick="submitform()" />
EDIT: In response to discussion in comments:
This doesn't work if you have only one text field - but it may be that is the desired behaviour in that case.
The other issue is that this relies on Javascript to submit the form. This may be a problem from an accessibility point of view. This can be solved by writing the <input type='button'/> with javascript, and then put an <input type='submit' /> within a <noscript> tag. The drawback of this approach is that for javascript-disabled browsers you will then have form submissions on ENTER. It is up to the OP to decide what is the desired behaviour in this case.
I know of no way of doing this without invoking javascript at all.
In short answer in pure Javascript is:
<script type="text/javascript">
window.addEventListener('keydown', function(e) {
if (e.keyIdentifier == 'U+000A' || e.keyIdentifier == 'Enter' || e.keyCode == 13) {
if (e.target.nodeName == 'INPUT' && e.target.type == 'text') {
e.preventDefault();
return false;
}
}
}, true);
</script>
This only disables the "Enter" keypress action for input type='text'. Visitors can still use "Enter" key all over the website.
If you want to disable "Enter" for other actions as well, you can add console.log(e); for your your test purposes, and hit F12 in chrome, go to "console" tab and hit "backspace" on the page and look inside it to see what values are returned, then you can target all of those parameters to further enhance the code above to suit your needs for "e.target.nodeName", "e.target.type" and many more...
See my detailed answer for a similar question here
I've always done it with a keypress handler like the above in the past, but today hit on a simpler solution. The enter key just triggers the first non-disabled submit button on the form, so actually all that's required is to intercept that button trying to submit:
<form>
<div style="display: none;">
<input type="submit" name="prevent-enter-submit" onclick="return false;">
</div>
<!-- rest of your form markup -->
</form>
That's it. Keypresses will be handled as usual by the browser / fields / etc. If the enter-submit logic is triggered, then the browser will find that hidden submit button and trigger it. And the javascript handler will then prevent the submision.
All the answers I found on this subject, here or in other posts has one drawback and that is it prevents the actual change trigger on the form element as well. So if you run these solutions onchange event is not triggered as well. To overcome this problem I modified these codes and developed the following code for myself. I hope this becomes useful for others.
I gave a class to my form "prevent_auto_submit" and added the following JavaScript:
$(document).ready(function()
{
$('form.prevent_auto_submit input,form.prevent_auto_submit select').keypress(function(event)
{
if (event.keyCode == 13)
{
event.preventDefault();
$(this).trigger("change");
}
});
});
I've spent some time making this cross browser for IE8,9,10, Opera 9+, Firefox 23, Safari (PC) and Safari(MAC)
JSFiddle Example: http://jsfiddle.net/greatbigmassive/ZyeHe/
Base code - Call this function via "onkeypress" attached to your form and pass "window.event" into it.
function stopEnterSubmitting(e) {
if (e.keyCode == 13) {
var src = e.srcElement || e.target;
if (src.tagName.toLowerCase() != "textarea") {
if (e.preventDefault) {
e.preventDefault();
} else {
e.returnValue = false;
}
}
}
}
stopSubmitOnEnter (e) {
var eve = e || window.event;
var keycode = eve.keyCode || eve.which || eve.charCode;
if (keycode == 13) {
eve.cancelBubble = true;
eve.returnValue = false;
if (eve.stopPropagation) {
eve.stopPropagation();
eve.preventDefault();
}
return false;
}
}
Then on your form:
<form id="foo" onkeypress="stopSubmitOnEnter(e);">
Though, it would be better if you didn't use obtrusive JavaScript.
Preventing "ENTER" to submit form may inconvenience some of your users. So it would be better if you follow the procedure below:
Write the 'onSubmit' event in your form tag:
<form name="formname" id="formId" onSubmit="return testSubmit()" ...>
....
....
....
</form>
write Javascript function as follows:
function testSubmit(){
if(jQuery("#formId").valid())
{
return true;
}
return false;
}
(OR)
What ever the reason, if you want to prevent the form submission on pressing Enter key, you can write the following function in javascript:
$(document).ready(function() {
$(window).keydown(function(event){
if(event.keyCode == 13) {
event.preventDefault();
return false;
}
});
});
thanks.
To prevent form submit when pressing enter in a textarea or input field, check the submit event to find what type of element sent the event.
Example 1
HTML
<button type="submit" form="my-form">Submit</button>
<form id="my-form">
...
</form>
jQuery
$(document).on('submit', 'form', function(e) {
if (e.delegateTarget.activeElement.type!=="submit") {
e.preventDefault();
}
});
A better solution is if you don't have a submit button and you fire the event with a normal button. It is better because in the first examlple 2 submit events are fired, but in the second example only 1 submit event is fired.
Example 2
HTML
<button type="button" onclick="$('#my-form').submit();">Submit</button>
<form id="my-form">
...
</form>
jQuery
$(document).on('submit', 'form', function(e) {
if (e.delegateTarget.activeElement.localName!=="button") {
e.preventDefault();
}
});
In my case, this jQuery JavaScript solved the problem
jQuery(function() {
jQuery("form.myform").submit(function(event) {
event.preventDefault();
return false;
});
}
You will find this more simple and useful :D
$(document).on('submit', 'form', function(e){
/* on form submit find the trigger */
if( $(e.delegateTarget.activeElement).not('input, textarea').length == 0 ){
/* if the trigger is not between selectors list, return super false */
e.preventDefault();
return false;
}
});
How about:
<asp:Button ID="button" UseSubmitBehavior="false"/>
Add this tag to your form - onsubmit="return false;"
Then you can only submit your form with some JavaScript function.
Please check this article How to prevent ENTER keypress to submit a web form?
$(“.pc_prevent_submit”).ready(function() {
$(window).keydown(function(event) {
if (event.keyCode == 13) {
event.preventDefault();
return false;
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class=”pc_prevent_submit” action=”” method=”post”>
<input type=”text” name=”username”>
<input type=”password” name=”userpassword”>
<input type=”submit” value=”submit”>
</form>
You can trap the keydown on a form in javascript and prevent the even bubbling, I think. ENTER on a webpage basically just submits the form that the currently selected control is placed in.
This link provides a solution that has worked for me in Chrome, FF, and IE9 plus the emulator for IE7 and 8 that comes with IE9's developer tool (F12).
http://webcheatsheet.com/javascript/disable_enter_key.php
Another approach is to append the submit input button to the form only when it is supposed to be submited and replace it by a simple div during the form filling
Simply add this attribute to your FORM tag:
onsubmit="return gbCanSubmit;"
Then, in your SCRIPT tag, add this:
var gbCanSubmit = false;
Then, when you make a button or for any other reason (like in a function) you finally permit a submit, simply flip the global boolean and do a .submit() call, similar to this example:
function submitClick(){
// error handler code goes here and return false if bad data
// okay, proceed...
gbCanSubmit = true;
$('#myform').submit(); // jQuery example
}
I Have come across this myself because I have multiple submit buttons with different 'name' values, so that when submitted they do different things on the same php file. The enter / return button breaks this as those values aren't submitted.
So I was thinking, does the enter / return button activate the first submit button in the form?
That way you could have a 'vanilla' submit button that is either hidden or has a 'name' value that returns the executing php file back to the page with the form in it.
Or else a default (hidden) 'name' value that the keypress activates, and the submit buttons overwrite with their own 'name' values.
Just a thought.
How about:
<script>
function isok(e) {
var name = e.explicitOriginalTarget.name;
if (name == "button") {
return true
}
return false;
}
</script>
<form onsubmit="return isok(event);">
<input type="text" name="serial"/>
<input type="submit" name="button" value="Create Thing"/>
</form>
And just name your button right and it will still submit, but text fields i.e. the explicitOriginalTarget when you hit return in one, will not have the right name.
If none of those answers are working for you, try this. Add a submit button before the one that actually submits the form and just do nothing with the event.
HTML
<!-- The following button is meant to do nothing. This button will catch the "enter" key press and stop it's propagation. -->
<button type="submit" id="EnterKeyIntercepter" style="cursor: auto; outline: transparent;"></button>
JavaScript
$('#EnterKeyIntercepter').click((event) => {
event.preventDefault(); //The buck stops here.
/*If you don't know what this if statement does, just delete it.*/
if (process.env.NODE_ENV !== 'production') {
console.log("The enter key was pressed and captured by the mighty Enter Key Inceptor (⌐■_■)");
}
});
This worked for me.
onkeydown="return !(event.keyCode==13)"
<form id="form1" runat="server" onkeydown="return !(event.keyCode==13)">
</form>
Here's how I'd do it:
window.addEventListener('keydown', function(event)
{
if (event.key === "Enter" && event.target.tagName !== 'TEXTAREA')
{
if(event.target.type !== 'submit')
{
event.preventDefault();
return false;
}
}
});
put into javascript external file
(function ($) {
$(window).keydown(function (event) {
if (event.keyCode == 13) {
return false;
}
});
})(jQuery);
or somewhere inside body tag
<script>
$(document).ready(function() {
$(window).keydown(function(event) {
alert(1);
if(event.keyCode == 13) {
return false;
}
});
});
</script>
I had the same problem (forms with tons of text fields and unskilled users).
I solved it in this way:
function chkSubmit() {
if (window.confirm('Do you want to store the data?')) {
return true;
} else {
// some code to focus on a specific field
return false;
}
}
using this in the HTML code:
<form
action="go.php"
method="post"
accept-charset="utf-8"
enctype="multipart/form-data"
onsubmit="return chkSubmit()"
>
In this way the ENTER key works as planned, but a confirmation (a second ENTER tap, usually) is required.
I leave to the readers the quest for a script sending the user in the field where he pressed ENTER if he decide to stay on the form.
I have a small quiz and am trying to get it so that after a user enters their answer, they can click submit button or press the enter key on their keyboard. I have tried using a callback function to capture both instances.
<form>
<input id="answer"></input>
<button id="btn" class="submit">SUBMIT</button>
</form>
var callback = function() {
var myAnswer = document.getElementById('answer').value;
if (myAnswer == "y" || myAnswer == "Y" ) {
$('.content-bd').html("<p>Well done!<p>");
}
else {
$('.content-bd').html("<p>Try again<p>");
}
};
$("input").keypress(function() {
if (event.which == 13) callback();
});
$('#btn').click(callback);
You are missing to collect the event.
$("input").keypress(function(event) {
if (event.which == 13) callback();
});
There are at least four problems:
The default type of a button is submit, so clicking that button will submit the form (and refresh the page). If you don't want that, add type="button" to the button.
input tags are void tags, you never write </input>
As AjAX. says, you've forgotten to declare the event parameter in your keypress callback, so you're relying on the global event, which doesn't exist on Firefox. (It would work on Chrome or IE.)
Some browsers submit the form if it has a single input and the user presses Enter. If you don't want that to happen, prevent form submission.
So:
var callback = function() {
var myAnswer = document.getElementById('answer').value;
if (myAnswer == "y" || myAnswer == "Y" ) {
$('.content-bd').html("<p>Well done!<p>");
}
else {
$('.content-bd').html("<p>Try again<p>");
}
};
$("input").keypress(function(event) {
if (event.which == 13) callback();
});
$('#btn').click(callback);
$("form").submit(false);
<form>
<input id="answer" type="text">
<button type="button" id="btn" class="submit">SUBMIT</button>
</form>
<div class="content-bd"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Its keydown function not keypress along with passing event.
<input type="text" id="txt"/>
$('#txt').keydown(function (e){
if(e.keyCode == 13){
alert('you pressed enter ^_^');
}
})
What I actually prefer to do is register even on the wrapping form. This way uses can interact with the page as they normally would have.
$('form').submit(function (e) {
e.preventDefault();
...
});
This way user can both press one of the submit buttons or hit enter while input fields are focused.
e.preventDefault() is used to prevent browser from actually submitting the form, which would cause page to be refreshed.
Another benefit of this approach is that, in future, if form is changed and new fields/submit buttons are added, event will still e handled properly.
Cheers.
This is a complete revision of my initial question, all unnecessary resources and references were deleted
I am tying the same event listener to 2 different elements: a button and Enter key, and it looks like the following:
var funcelement = function(){
//function code
};
$('#buttonID').click(funcelement);
$('#inputID').keyup(function () {
if (event.which == 13) {
$('#buttonID').trigger('click');
}
})
What I am trying to do is to prevent propagation of the enter key press if focus is on the submit button(#buttonID) by using preventDefault().
So I tried various combinations to make it work. The following is the latest result on my attempts
$('#inputID').keyup(function () {
var hasfocus = $('#buttonID').is(':focus') || false;
if (event.which == 13) {
if (!hasfocus) {
event.preventDefault();
$('#buttonID').trigger('click');
//hasfocus = true;
}
else {
//event.preventDefault();
//$('#buttonID').trigger('click');
}
}
})
After I enter a text into an input box and press Enter key, a confirmation window with yes/cancel buttons pops up with focus on yes button. Once I press Enter again, another window confirming that changes were made pops up with Ok button focused on it. Once I press Enter again, everything I need is being made.
However, there is one problem: after the last step is done, I am going back to the if (!hasfocus) line.
How do I prevent that from happening? Once the stuff I need is done - I don't want to go into that line again.
You can pass a parameter to into the function and stop the propagation there like so:
var funcelement = function(event, wasTriggeredByEnterKey){
if (wasTriggeredByEnterKey && $('#buttonID').is(':focus')) {
event.stopPropagation;
}
//function code
};
$('#buttonID').click(funcelement);
$('#inputID').keyup(function () {
if (event.which == 13) {
$('#buttonID').trigger('click', [true]);
}
}
)
UPDATE
In order to answer your revised issue, you should use the "keydown" event rather than "keyup" when working with alerts. This is because alerts close with the "keydown" event but then you are still triggering the "keyup" event when you release the enter key. Simply change the one word like this:
$('#inputID').keydown(function () {
var hasfocus = $('#buttonID').is(':focus') || false;
if (event.which == 13) {
if (!hasfocus) {
event.preventDefault();
$('#buttonID').trigger('click');
//hasfocus = true;
}
else {
//event.preventDefault();
//$('#buttonID').trigger('click');
}
}
})
I have a web application where on one specific screen I have to make sure the user clicked the button using the mouse as opposed to just pressing enter or space.
I have written this code:
$('button').keydown(function (e) {
if (e.which === 10 || e.which === 13 || e.which === 32) {
return false;
}
});
However, this only works for enter. The form can still be submitted by pressing space on a button. I am just wondering what caused this inconsistency and how to get around it?
Edit:
Example fiddle: http://jsfiddle.net/billccn/3JmtY/1/. Check the second check box and pressing enter while the focus is on the button will have no effect. If I further disable the input and expand the keydown trapping to the whole form, then enter cannot be used to submit the form.
Edit 2:
I do have a backup plan which is replacing the button with a link or even a plain div and use the click event to submit the form programmatically. However, extra work is required to make it look like a button so I'd rather use a button is possible.
Just found out: handling space (32) on keyup will prevent the click event.
Updated fiddle: http://jsfiddle.net/3JmtY/2/
Missed the Point of your Question. After some googleing if found the following trick:
Bind the keypress event to your from and listen to it's keycode. If the keycode is 13
(enter), prevent all default actions (event.preventDefaul()) and prevent further event bubbeling ( return false; ).
Her is a fiddler code example:
HTML:
<form id="target" action="destination.html">
<input type="text" value="Hello there" />
<input type="submit" value="Go" />
</form>
<div id="other">Trigger the handler</div>
JavaScript:
$('#target').keypress(function (event) {
var code = event.keyCode || event.which;
if (code == 13) {
event.preventDefault();
return false;
}
});
$('#target').submit(function (event, data2) {
debugger;
alert('test');
return false;
});
Fiddler: http://jsfiddle.net/ggTDs/
Note that the form is not submited when enter is clicked!
Use below code. 13 for Enter key and 32 for Spacebar.
$("#form_id").on('keydown keyup keypress', function( e ) {
if ( e.keyCode == 13 || e.which == 13 || e.which == 32 ) {
e.preventDefault();
return false;
}
});
It would appear to be a simple requirement, but I haven't found a simple solution yet:
In a JSF 1.2 / Richfaces 3.3 webapp, I have a form with input components of various types, followed by an <a4j:commandButton> and a <h:commandButton>. The former resets the form, the second performs some action with the data entered.
My goal is to have this action triggered when the user presses the enter key while entering data. How can I do that?
Edit: Generally, I have more than one <h:commandButton> per <form>. I'd like to designate a particular one as default action. Also, I'd like the solution to play nice with AJAX (which we use extensively).
Unless you are using MSIE browser and in reality you've only one input field without a button, it should just be the default behaviour. Otherwise probably some (autogenerated) JS code has messed it up.
If you don't have textareas in the form, an easy fix would be the following:
<h:form onkeypress="if (event.keyCode == 13) submit();">
Or if you have textareas and you don't want to repeat the same keypress functions over all non-textarea input elements, run the following script during window onload.
for (var i = 0; i < document.forms.length; i++) {
var inputs = document.forms[i].getElementsByTagName('input');
for (var j = 0; j < inputs.length; j++) {
inputs[j].onkeypress = function(e) {
e = e || window.event;
if (event.keyCode == 13) {
this.form.submit();
return false;
}
};
}
}
Building on BalusC's answer I came up with the following (tested on IE and FireFox):
<h:form id="form" onkeypress="ifEnterClick(event, #{rich:element('searchButton')});">
where ifEnterClick is defined by:
/**
* Handler for onkeypress that clicks {#code targetElement} if the
* enter key is pressed.
*/
function ifEnterClick(event, targetElement) {
event = event || window.event;
if (event.keyCode == 13) {
// normalize event target, so it looks the same for all browsers
if (!event.target) {
event.target = event.srcElement;
}
// don't do anything if the element handles the enter key on its own
if (event.target.nodeName == 'A') {
return;
}
if (event.target.nodeName == 'INPUT') {
if (event.target.type == 'button' || event.target.type == 'submit') {
if (strEndsWith(event.target.id, 'focusKeeper')) {
// inside some Richfaces component such as rich:listShuttle
} else {
return;
}
}
}
if (event.target.nodeName =='TEXTAREA') {
return;
}
// swallow event
if (event.preventDefault) {
// Firefox
event.stopPropagation();
event.preventDefault();
} else {
// IE
event.cancelBubble = true;
event.returnValue = false;
}
targetElement.click();
}
}
Edit: Since selecting a value from Firefox form auto completion using the enter key fires a keydown event, but no keypress event, using onkeypress is preferable to onkeydown.
Just put this code in your JS file:
$('input,textarea').live('keydown',function(e) { // submit forms on pressing enter while focus is on any input elmnt inside form
if (e.keyCode == 13) {
$(this).closest('form').submit();
}
});
In retrospect, solving this problem with the means HTML provides is far less brittle and easier to maintain, as the answers to the following related question show:
Multiple submit buttons on HTML form – designate one button as default
Use the PrimeFaces component:
<!-- Default button when pressing enter -->
<p:defaultCommand target="submit"/>
Use this in combination with a focus component and you will rock!
<!-- Focus on first field, or first field with error -->
<p:focus context="feesboek"/>