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 am currently running this as I don't want users to press enter on their keyboard to launch an input and it works.
jQuery(window).keydown(function(event){
if(event.keyCode == 13) {
event.preventDefault();
return false;
}
});
However I have one part of the site where this shouldn't be avoided and i tried the following but it didn't work
if(jQuery(".tab-pane").is("#step6")) {
jQuery(window).keydown(function(e){
if(e.keyCode == 13) {
return true;
}
});
}
I guess the first overrides the second
Yes..first function is replace the second one.so use like this .Include the second function inside the first .Events are same, condition only different
jQuery(window).keydown(function(event){
if(event.keyCode == 13) {
if(jQuery(".tab-pane").is("#step6")) {
return true;
}
else{
event.preventDefault();
return false;
}
}
});
You may need to slightly tweek the code & check this condition inside keydown
jQuery(window).keydown(function(event) {
// checking current keycode
if (13 == event.keyCode) {
// the is condition
if (jQuery(".tab-pane").is("#step6")) {
return !0; // will return true
}
event.preventDefault(); // otherwise will prevent default behaviour
return !1 // will return false
}
});
I suggest attaching the event of the click to each input not to the window :
<input type="text" onkeypress="myFunction(event)">
myFunction() should be like this :
function myFunction(e) {
if (e.keyCode == 13) {
//do whatever you want
}
}
Hope this was useful
Try using classes to make it easy.. just add the class prevent-enter on the inputs you want to avoid the keypress.
$(document).ready(function() {
$('.prevent-enter').keydown(function(e) {
if (e.keyCode == 13) {
e.preventDefault();
return false;
}
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="get" action="javascript:alert('form submitted');">
<input class="prevent-enter" placeholder="This prevents enter keypress" /><br>
<input class="" placeholder="This accepts enter keypress" /><br>
<input type="submit" />
</form>
I have a script that remove "disabled" attr of my button when my 2 vars has 3 and 5 characters respectively.
But when I deleted my characters it doesnt count back, and add again the "disabled" attr to my button.
I dont know how to do it. Any suggestions ?
FIDDLE: http://jsfiddle.net/CCwKp/
HTML
<form action="" method="" class="login">
<ul class="userLogin">
<li>
<input type="text" placeholder="E-mail" class="user" />
</li>
<li>
<input type="password" placeholder="Senha" class="pass" />
</li>
</ul>
<button disabled />test</button>
</form>
JS
$(function () {
var user = 0;
var pass = 0;
function userPassAlert() {
if (user >= 3 && pass >=5) {
$('button').removeClass('disabled').addClass('available').removeAttr("disabled");
} else {
$('button').removeClass('available').addClass('disabled').attr("disabled");
}
};
$(".user").on('focus keypress', function() {
user++;
console.log(user);
userPassAlert();
});
$(".pass").on('focus keypress', function() {
pass++;
console.log(pass);
userPassAlert()
});
$('button').on('click', function (e) {
e.preventDefault();
if (user >= 3 && pass >=5) {
alert("done");
}
else {
return false;
}
});
});
Three things:
To add the "disabled" attribute back to the button, it has to be added as such:
$(".this").attr("disabled","disabled");
The counter is always adding to the user/pass when there is a mouse click or keypress so it will always go up and never down. If we change this to check the length of the value in the input when there is a mouse or key action, it will verify the actual length existing in the input field. You can do this by using:
user=$(".user").val().length;
Keyup is better to handle backspace than keypress. Replacing this in your "on" functions will provide a more accurate result.
JS Fiddle Here
You increment the user and pass on every keypress, even if you remove a character. I
would instead check the length of the values in the fields in your method userPassAlert():
function userPassAlert() {
if ($('.user').val().length >= 3 && $('.pass').val().length >=5) {
$('button').removeClass('disabled').addClass('available').prop("disabled", false);
} else {
$('button').removeClass('available').addClass('disabled').prop("disabled", true);
}
};
If I create the click events and their handler on my own, it is no problem for me to execute event.preventdefault() at the right place. But if there is an element, which already has registered click events and corresponding handler, I want to deactivate its further working (e.g. submitting) in a certain case.
This is the example:
There is a submit button on the page, with registered click elements (maybe about hundred validation routines.. ) and a variable (al) with a certain value. Be the instantaneous value of this variable = 5 (it is not the desired certain case -> with value = 3).
HTML
// other form elements
<input type="submit" name="next" value="go"/>
JavaScript with jQuery
var al = 3;
$("input[type='submit'][name='next']").click(
function(event) {
if (al != 3) {
alert (al+': Not OK');
event.preventDefault();
} else {
alert ('OK');
}
}
);
In this example I cannot prevent the form is being submitted. What is my mistake?
EDIT: event.preventDefault ist not the problem, sublime (my editor) corrects it anyway.
----- I WANT TO SIMPLIFY THE QUESTION ---------
That is a SubmitButon (this time from yii in the original context):
VIEW
echo CHtml::submitButton(
Yii::t ('Somethin', 'next'),
array(
'name' => 'next',
'onclick' => "checkDetails()"
));
JS
checkDetails() {
PREVENT_SUBMITTING
}
How should PREVENT_SUBMITTING look? What would prevent submitting in this case, without any condition?
change
event.preventdefault();
to
event.preventDefault();
you have to write the "D" as capital letter.
You can do this two ways
$("input[type='submit'][name='next']").click(
function(event) {
if (al != 3) {
alert (al+': Not OK');
event.preventDefault();
} else {
alert ('OK');
}
}
);
or
$("input[type='submit'][name='next']").click(
function(event) {
if (al != 3) {
alert (al+': Not OK');
return false;
} else {
alert ('OK');
return true;
}
}
);
Now I have a working solution:
VIEW
echo PHtml::submitButton(Yii::t('Something', 'next'),
array(
'name' => 'next',
'onclick' => "return checkDetails(event)",
)
);
jQuery
function checkDetails (event) {
event.preventDefault();
event.returnValue =false; // for IE
return false;
}
$("input[type='submit'][name='next']").click(
function(event) {
if (al != 3) {
alert (al+': Not OK');
event.preventDefault();
} else {
alert ('OK');
}
}
);
Try this Change event.preventDefault();
$("input[type='submit'][name='next']").click(
function(event) {
if (al != 3) {
alert (al+': Not OK');
event.preventDefault();
} else {
alert ('OK');
}
}
);
I recently needed to use .off() instead of .preventDefault(). I needed to intercept and block one event handler while still allowing the main click event to bubble up. Might be what you need.
Besides from this problem I ll suggestion you to separate the validation part e. g
Add another form input e.g proceed
<input type="hidden" name="proceed" value="0"/>
<input type="submit" name="next" value="go"/>
Add custom validation method
jQuery.validator.addMethod("validateSteps", function(value, element) {
return value == 3 ? false : true;
}, "*");
Add validation rule to you form
$("#your_form_id").validate({
rules: {
"proceed": {
validateSteps: true
}
},
messages: {
"proceed": {
validateSteps: "custom message"
}
}
});
You have to set proper value to proceed input field before. This way you do not need to wade through event issues. And its more customizable e.g if you have ten steps with different validation requirements on each step
I have the following html form
<form action="/newPost" id="submit_new" method="get"><div class="iwill">
<div class="iwill-holder">
<div class="txt"></div><div class="f"><input class="text" id="quickpost" name="quickpost" type="text" value=""></div>
<div class="img regularProgress" alt="Processing..."><input alt="Continue" class="iwill-btn movable" id="continue_submit" src="<?=$config['http']?>images/btn-2-continue-gray.png" type="image"></div>
</div>
</div>
</form>
and here is the jquery function :
$('#submit_new').submit(function() {
var error = 0;
var quickpost = $("#quickpost").val();
if( quickpost == '' ) {
$("#quickpost").effect("shake", { times:3 }, 50);
$('#quickpost').css("color","red");
$('#quickpost').css("border","red 1px solid");
error = 1;
}else{
$('#quickpost').css("border","gray 1px solid");
$('#quickpost').css("color","black");
error = 0;
}
if(errorCounter > 0){
return false;
}else{
$.ajax({
url: 'sendPost.php?quickpost='+quickpost,
success: function(data) {
$('#result').prepend(data).slideDown('slow', function() {});
}
});
}
return false;
});
technically I am trying to post the form values using ajax, but whatever I do the form still gets submitted to action page. I have tried to even make all paths lead to false but its not working
Try preventing the default behavior
$('#submit_new').click(function(e) {
e.preventDefault();
...
You also have a typo
if(errorCounter > 0){
return false;
}else{
should be:
if(error > 0){
return false;
}else{
$('#submit_new').submit(function(e) {
e.preventDefault();
//other stuff
});
You need a preventDefault() in the submit function.
I got a version still use return false to prevent form submit
http://jsfiddle.net/pKR6G/2/
NB: I've commented out the line of shake effect so I don't need to include jQueryUI.
The event listener method does not care what you return from a listener function. You need to use the jquery preventdefault method on the passed in event object.