Prevent user hitting Enter except Textarea - javascript

I have a fairly complex form which has multiple stages with many different text fields and text areas. The environment it is used within used barcodes which hit enter by default, and that is by choice as they scan a multitude of products using them so turning the enter function off has become a no-go.
I am using a form wizard script which handles client-side validation during the input stage. This script is interrupted by the enter key being hit during filling out the form and refuses to submit until the page is refreshed.
Submit <i class="m-icon-swapright m-icon-white"></i>
I have the following code which works to prevent enter on the form and allows the form to submit when the link above is clicked.
$(window).keydown(function (event) {
if (event.keyCode == 13) {
event.preventDefault();
return false;
}
});
However this prevents enter being used within textarea. I did a bit of research and tried using the is() operator from jQuery
$(document).ready(function () {
$(window).keydown(function (event) {
if (event.keyCode == 13 && !event.is("textarea")) {
event.preventDefault();
return false;
}
});
});
This doesn't work, it fails to prevent the enter key in inputs and stalls the form from submitting as it did prior.
Finally this is the javascript that handles submitting the form if validation passes on the form
$('#form_wizard_1 .button-submit').click(function () {
// Can put more onsubmit processing here
document.getElementById('submit_form').submit();
}).hide();
Can anyone suggest how I can prevent the enter key on all inputs EXCEPT for textareas. I don't pretend to be a JavaScript developer, although I am trying to learn as I go. The following are articles I have read and either attempted to adapt code or failed to understand how it would apply to me in the correct manner:
Prevent users from submitting a form by hitting Enter
Prevent Users from submitting form by hitting enter #2
disable enter key on page, but NOT in textarea
*In regards to the last link, I need a global resolution that automatically prevents it on all textareas that may exist within the form.
As always, thank you for your assistance.

JavaScript
Use KeyboardEvent.key and Element.matches(selectors)
document.querySelector("#myForm").addEventListener("keydown", (evt) => {
if (evt.key === "Enter" && !evt.target.matches("textarea")) {
evt.preventDefault(); // Don't trigger form submit
console.log("ENTER-KEY PREVENTED ON NON-TEXTAREA ELEMENTS");
}
});
<form id="myForm">
<input name="inp" placeholder="Click here and hit Enter" type="text">
<textarea name="txa" placeholder="Click here and hit Enter"></textarea>
<input type="submit">
</form>
jQuery
Use !$(event.target).is("textarea")
Also use Event.key, or use Event.which (instead of Event.keyCode; jQuery normalizes it for cross-browser)
jQuery(function($) { // DOM ready
$('form').on('keydown', function(ev) {
if (ev.key === "Enter" && !$(ev.target).is('textarea')) {
ev.preventDefault(); // Don't trigger form submit
console.log("ENTER-KEY PREVENTED ON NON-TEXTAREA ELEMENTS");
}
});
});
<form>
<input name="inp" placeholder="Click here and hit Enter" type="text">
<textarea name="txa" placeholder="Click here and hit Enter"></textarea>
<input type="submit">
</form>
<script src="//code.jquery.com/jquery-3.6.1.js"></script>

Related

Remotely preventDefault() a Form in another Function

I'm not really sure how to ask/word this question but...
How can I prevent a form from submitting from another jQuery function? Basically, I have input fields with auto-complete functionality where the end-user can navigate through the results by using the up-and-down arrow keys. The end-user can press the Enter key to make a selection however that makes the form submit. I would like to prevent that from happening.
$('body').on('click keyup', '.inputField1', function(e) {
if(e.keyCode===13){
// Attempting to remotely prevent the form from submitting
var form = $(this).closest('form');
form.preventDefault();
form.stopPropagation();
return false;
}
// auto-complete logic below
// ...
});
Please note that I've tried adding the logic above under $('#myForm1').submit(function(e){ ... but the enter key was not detected upon input.
Assuming you're trying to prevent the form submitting when the user hits "enter" while an input field is in focus:
You want to attach this handler to the input field itself, and should use the keydown or keypress event rather than keyup (which happens after the form submission has started). What you're preventing isn't the form submit, but the default action of the event which triggers the form submit, so call preventDefault() on the event, not on the form.
event.keyCode and event.which are deprecated, but still universally supported. The currently "correct" way to do this would be if (event.key === "Enter") but this may not work in some older browsers (and note that current IE and Edge still use nonstandard identifiers for some keys.)
// It's not necessary to delegate the event from 'body', unless the form field is added to the DOM after this is called.
$('.inputField1').on('keydown', function(e) {
if (e.keyCode === 13) {
e.preventDefault();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="https://example.com">
<input class="inputField1">
<input type="submit">
</form>
Your problem is keyup on the input triggers before submit on the form.
If you change your event to keypress you'll find you can intercept the submit event before form submission.
Also, you should be using event.which instead of event.keyCode - jQuery standarizes .which but I don't think it does the same for .keyCode.
The following code sample will show this in action. The first text field will intercept when you press enter, the second will not.
(function($) {
$(function() {
$('body').on('keypress', '.a', function(event) {
if(event.which == 13) {
alert('You pressed enter');
event.preventDefault();
}
});
});
})(jQuery);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="get" action="https://www.stackoverflow.com" onsubmit="alert('submit event');return false;">
<input class="a" type="text">
<input class="b" type="text">
<input type="submit">
</form>

Intercepting a submit not working

I have a number of fields that are either filled (inputs) or selected (dropdowns) that working together to create a new page.
I'm attempting to validate the entries and prevent the page creation if anything is wrong with the inputs. No form is being used.
The problem is the $("#netsubmit").submit(function( event )) never gets run when the submit is clicked. No errors are thrown, no indication why its not processing.
My html for the input is:
<input id="netsubmit" type="submit" value="Submit" onClick="newNet()"
title="Submit The New Net">
My JQuery javascript is:
$(document).ready(function () {
$("#netsubmit").submit(function( event ) {
alert("in it");
var callentered = $("#callsign").val();
if (callentered == "") {
event.preventDefault();
alert("Please enter a call sign first.");
$("#callsign").focus();
}
});
});
It is likely not working because as you said you aren't using a form element. From the jquery docs:
The submit event is sent to an element when the user is attempting to submit a form. It can only be attached to form elements
You could use the function specified by your onclick event onClick="newNet()" to validate the data.
.submit() can only be used with <form> elements, as stated in the documentation:
It can only be attached to <form>elements.
If you do not want to use the form tag, you can switch to using .click() instead, like so:
$("#netsubmit").click(function(event) {
alert("in it");
});
If you read the documentation for submit on MDN it explicitly says
The submit event is fired when a form is submitted.
Note that submit is fired only on the form element, not the button or
submit input. (Forms are submitted, not buttons.)
if you do
<form id="myform">
<input id="netsubmit" type="submit" value="Submit" onClick="newNet()" title="Submit The New Net">
</form>
and then change the code
$(document).ready(function () {
$("#myform").submit(function( event ) {
alert("in it");
var callentered = $("#callsign").val();
if (callentered == "") {
event.preventDefault();
alert("Please enter a call sign first.");
$("#callsign").focus();
}
});
});
it works fine

jquery disable form submit on enter

I have the following javascript in my page which does not seem to be working.
$('form').bind("keypress", function(e) {
if (e.keyCode == 13) {
e.preventDefault();
return false;
}
});
I'd like to disable submitting the form on enter, or better yet, to call my ajax form submit. Either solution is acceptable but the code I'm including above does not prevent the form from submitting.
If keyCode is not caught, catch which:
$('#formid').on('keyup keypress', function(e) {
var keyCode = e.keyCode || e.which;
if (keyCode === 13) {
e.preventDefault();
return false;
}
});
EDIT: missed it, it's better to use keyup instead of keypress
EDIT 2: As in some newer versions of Firefox the form submission is not prevented, it's safer to add the keypress event to the form as well. Also it doesn't work (anymore?) by just binding the event to the form "name" but only to the form id. Therefore I made this more obvious by changing the code example appropriately.
EDIT 3: Changed bind() to on()
Usually form is submitted on Enter when you have focus on input elements.
We can disable Enter key (code 13) on input elements within a form:
$('form input').on('keypress', function(e) {
return e.which !== 13;
});
DEMO: http://jsfiddle.net/bnx96/325/
Even shorter:
$('myform').submit(function() {
return false;
});
$('form').keyup(function(e) {
return e.which !== 13
});
The event.which property normalizes event.keyCode and event.charCode. It is recommended to watch event.which for keyboard key input.
which docs.
$(document).on('keyup keypress', 'form input[type="text"]', function(e) {
if(e.which == 13) {
e.preventDefault();
return false;
}
});
This solution works on all forms on website (also on forms inserted with ajax), preventing only Enters in input texts. Place it in a document ready function, and forget this problem for a life.
Most answers above will prevent users from adding new lines in a textarea field. If this is something you want to avoid, you can exclude this particular case by checking which element currently has focus :
var keyCode = e.keyCode || e.which;
if (keyCode === 13 && !$(document.activeElement).is('textarea')) {
e.preventDefault();
return false;
}
if you just want to disable submit on enter and submit button too use form's onsubmit event
<form onsubmit="return false;">
You can replace "return false" with call to JS function that will do whatever needed and also submit the form as a last step.
The simple way is to change type of button to button - in html and then add event in js...
Change from this:
<form id="myForm">
<button type="submit">Submit</button>
</form>
To
<form id="myForm">
<button type="button" id="btnSubmit">Submit</button>
</form>
And in js or jquery add:
$("#btnSubmit").click(function () {
$('#myForm').submit();
});
The overkill of having to capture and test every keystroke for the ENTER key really bugs me, so my solution relies on the following browser behavior:
Pressing ENTER will trigger a click event on the submit button (tested in IE11, Chrome 38, FF 31) **
(ref: http://mattsnider.com/how-forms-submit-when-pressing-enter/ )
So my solution is to remove the standard submit button (i.e. <input type="submit">) so that the above behavior fails because there's no submit button to magically click when ENTER is pressed. Instead, I use a jQuery click handler on a regular button to submit the form via jQuery's .submit() method.
<form id="myform" method="post">
<input name="fav_color" type="text">
<input name="fav_color_2" type="text">
<button type="button" id="form-button-submit">DO IT!</button>
</form>
<script>
$('#form-button-submit').click(function(){
$('#myform').submit();
});
</script>
Demo: http://codepen.io/anon/pen/fxeyv?editors=101
** this behavior is not applicable if the form has only 1 input field and that field is a 'text' input; in this case the form will be submitted upon ENTER key even if no submit button is present in the HTML markup (e.g. a search field). This has been standard browser behavior since the 90s.
You can do this perfectly in pure Javascript, simple and no library required. Here it is my detailed answer for a similar topic:
Disabling enter key for form
In short, here is the code:
<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 code is to prevent "Enter" key for input type='text' only. (Because the visitor might need to hit enter across the page) 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...
I don't know if you already resolve this problem, or anyone trying to solve this right now but, here is my solution for this!
$j(':input:not(textarea)').keydown(function(event){
var kc = event.witch || event.keyCode;
if(kc == 13){
event.preventDefault();
$j(this).closest('form').attr('data-oldaction', function(){
return $(this).attr('action');
}).attr('action', 'javascript:;');
alert('some_text_if_you_want');
$j(this).closest('form').attr('action', function(){
return $(this).attr('data-oldaction');
});
return false;
}
});
In firefox, when you at input and press enter, it will submit it's upper form. The solution is in the will submit form add this:
<input type="submit" onclick="return false;" style="display:none" />
$('#FormID').on('keyup keypress', function (e) {
var keyCode = e.keyCode || e.which;
if (keyCode === 13) {
e.preventDefault();
return false;
}
});
The following code will negate the enter key from being used to submit a form, but will still allow you to use the enter key in a textarea. You can edit it further depending on your needs.
<script type="text/javascript">
function stopRKey(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") || (node.type=="radio") || (node.type=="checkbox")) ) {return false;}
}
document.onkeypress = stopRKey;
</script>
3 years later and not a single person has answered this question completely.
The asker wants to cancel the default form submission and call their own Ajax. This is a simple request with a simple solution. There is no need to intercept every character entered into each input.
Assuming the form has a submit button, whether a <button id="save-form"> or an <input id="save-form" type="submit">, do:
$("#save-form").on("click", function () {
$.ajax({
...
});
return false;
});
Here is a simple JavaScript solution without using different variations of handling keydown or keypress events:
document.forms[0].addEventListener('submit', function(e) {
if(document.activeElement.getAttribute('type') !== 'submit') {
e.preventDefault();
}
});
Submitting the form will occur only when the active element on your page is the submit button.
So you can submit the form by clicking on your submit button or by pressing the ENTER key when the submit button has focus.
I heard which is not recommended, so change Best rated answer to this.
$('#formid').on('keyup keypress', function(e) {
if (e.key === 'Enter') {
e.preventDefault();
return false;
}
});
ref. https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/which
When the file is finished (load complete), the script detect each event for " Entry " key and he disable the event behind.
<script>
$(document).ready(function () {
$(window).keydown(function(event){
if(event.keyCode == 13) {
e.preventDefault(); // Disable the " Entry " key
return false;
}
});
});
</script>
Complete Solution in JavaScript for all browsers
The code above and most of the solutions are perfect.
However, I think the most liked one "short answer" which is incomplete.
So here's the entire answer. in JavaScript with native Support for IE 7 as well.
var form = document.getElementById("testForm");
form.addEventListener("submit",function(e){e.preventDefault(); return false;});
This solution will now prevent the user from submit using the enter Key and will not reload the page, or take you to the top of the page, if your form is somewhere below.
How about this:
$(":submit").closest("form").submit(function(){
$(':submit').attr('disabled', 'disabled');
});
This should disable all forms with submit buttons in your app.

Pressing Enter Always Submits Form

I have a simple text box and button type input on my page.
<input id="sText" type="text" />
<input id="sButton" type="button" value="button" />
I capture a button click using jQuery.
$("[id$=sButton]").click(function () {
...do Stuff
});
The above code works just fine as long as I manually click the button. I started running into problems when I wanted to use the "enter" key to click the button. No matter what I do, I cannot prevent the enter key from performing it's default submit function.
The first thing I did was change the input type from "submit" to "button".
I tried setting the form's onsubmit to onsubmit="return false;"
I tried using jQuery to capture the enter key event:
$("#sText").keyup(function (event) {
if (event.keyCode == 13) {
alert("Enter!");
// $("#sButton").click();
}
});
Every time I press the enter key, it's like I'm submitting the form, the whole page refreshes. The above jQuery code does capture the "enter" keystroke, but the form still submits and refreshes the page.
I'm not sure whats going on.
You need to cancel the action.
event.preventDefault();
BUT I believe you can only kill the form submission with keydown, not keyup.
Epascarello is right, you need to cancel the for submit with the code he gave you. But you should also change the button back to a submit type so that the ENTER key and Clicking the button do the same thing. That way you only have to handle the cancellation of the submit in one area.
<input id="sButton" type="submit" value="Submit" />
JQuery:
$("#YourFormId").submit(function(event){
event.preventDefault();
...do Stuff
});
This way one function handles the ENTER key and the button click.
EDIT: Put the event.preventDefault() as the first statement.

Submitting a form with the enter button in a form with several submit buttons

I have a form with a simple text field and multiple submit buttons. When the user presses enter, I want to submit the form with a specific submit button, but it looks like the form just chooses the first button instead. Is there any way to tell the browser which submit button to choose when user presses enter? Preferrably without javascript, but I'll take it if that's the only solution.
Edit: I have no other choice than having multiple submit buttons. This is a legacy app.
There's no way. The simplest solution is just to ensure that the first submit button in the form is the one you want triggered by the Enter button.
Note that this submit button can be a duplicate of a button elsewhere in the form, and it doesn't have to be visible.
You can use simple JS to catch the onkeypress event:
onkeypress="if ((event.keyCode | event.which) == 13) { document.getElementById('MySubmitButton').click(); return false; }"
Just add this to the textbox tag and replace "MySubmitButton" with the ID of the desired submit button.
Note: use ID, not name.
If you had the following HTML
<form id="form_one">
<input type="submit" value="Submit 1" />
</form>
<form id="form_two">
<input type="submit" value="Submit 2" />
</form>
Then you could have a bit of jQuery as follows
$(document).ready(function() {
$(this).keydown(function(e) {
if (e.keyCode == '13') {
$("#form_one").submit();
}
});
});
Obviously you'd have to put in the logic to decide which form to submit.
Also as far as I know if a control in "form_one" had focus and you hit enter it would automatically submit that form the control is contained within.
you can just define a javascript method on the "onclick" or "onkeypress" event of the button, from which u wanted to get the form submitted. But u have to define the process to occur in the javascript function

Categories

Resources