I had a jQuery / HTML code similar to this:
<form action="/SomeAction" method="post">
<input id="my-textbox" type="text" placeholder="Write something and press enter to continue..." />
</form>
<script type="text/javascript">
$(function() {
$('#my-textbox').keyup(function(e) {
var $textbox = $(this);
if ($textbox.val().length > 0 && e.keyCode == 13) {
$textbox.parent('form').submit();
}
});
});
</script>
The purpose was to automatically submit the form when the user pressed the Enter key. I regularly use Firefox so everything was OK for me until I tested in Google Chrome and Internet Explorer.
When I pressed the Enter key in the later browsers, sometimes I would get the form submitted twice. This was easy to notice because I would get duplicate entries in my DB and I'd see two POSTs using Fiddler.
After some testing, I found out that my problem was the jQuery code, since the textbox would submit automatically on enter without it, and using this code would produce a second POST in some browsers.
My questions are:
Why don't browsers smartly prevent the second form post (like Firefox did in my testing)?
Should I expect this behavior in all major browsers in all platforms?
Is there a way to improve this code so I perform the submit using JavaScript, but don't get the form submitted twice?
Why don't browsers smartly prevent the second form post (like Firefox did in my testing)?
That is the default behavior. What if you didn't have your script and the default behavior was such that the form wouldn't POST on enter.
Should I expect this behavior in all major browsers in all platforms?
Yes
Is there a way to improve this code so I perform the submit using JavaScript, but don't get the form submitted twice?
Use a global mutex variable and set it once the form POSTs - checking it on subsequent POSTs to validate. Or, return false from the keyup handler and stop the event propagation.
Some browsers will interpret an input button as a submit if there is only one button in the form. Just return false in your function to prevent the default behavior from submitting the form.
if ($textbox.val().length > 0 && e.keyCode == 13) {
$textbox.parent('form').submit();
return false;
}
Your form is being submitted right after the enter has been pressed (on keydown and before keyup fires) so you can do
$(function() {
$('#my-textbox').keydown(function(e){
if(e.keyCode==13) e.preventDefault();
});
$('#my-textbox').keyup(function(e) {
e.preventDefault();
var $textbox = $(this);
if($textbox.val().length > 0 && e.keyCode == 13) {
$textbox.parent('form').submit();
}
});
});
A simple test.
Add boolean variable that would be set to true after first submit and use that variable in your if condition. This would prevent accidental double click.
You should also prevent double submit in the application backend (many web frameworks have built-in mechanism for doing this, it easy to come up with custom solution as well).
Related
I know that this question has been asked before but I'm having particular trouble submitting my form when I press the enter key. I've tried multiple solutions but none have worked. When I try to press enter, the page refreshes and my typing is gone.
This is my HTML:
form class="nput">
<h1 class= "header">Member Login</h1>
<label class="text" for="pswd">Enter your password: </label>
<input class="form" type="password" id="pswd">
<input id="yeet" class="bttn" type="button" value="Submit" onclick="checkPswd();" />
</form>
And this is my Javascript:
<script type="text/javascript">
function checkPswd() {
var confirmPassword = "password";
var password = document.getElementById("pswd").value;
if (password == confirmPassword) {
window.location="members.html";
}
else{
alert("Password incorrect. Please try again.");
}
}
// Get the input field
var input = document.getElementById("pswd");
input.addEventListener("keyup", function(event) {
if (event.keyCode === 13) {
alert("hi there");
event.preventDefault();
document.getElementById("yeet").click();
}
});
</script>
I cannot figure out this small issue and I would appreciate any help! Thanks!
EDIT: I just wanted to let everyone know that I do in fact know that there is little security that comes with this method but I mostly want the password for looks not function.
You got something backwards there - you are submitting the form with Enter. This is exactly the problem though, it seems as if you don't want to submit it, instead you want to run your client-side handler checkPswd. (You do know that everyone can read the correct password in their browser console though, right? So it's no protection.)
What you want to do is change the onclick on the button to an onsubmit on the form itself! Then your code will run no matter in what way (keyboard or mouse) the form is submitted.
You can delete the whole keyup stuff then.
(The reason your attempt to "click" the button in JavaScript wasn't working is because unlike jQuery's click method, the vanilla click will only execute the default action and not any attached click event handlers like yours. Also, it is kinda backwards because you should react on the common ground of both clicking the button and pressing Enter, which is submitting the form.)
To echo a comment above - you want to use the onsubmit handler on the <form> element - this will allow users to submit the form both by clicking the <button type="submit> button, and by hitting the enter key in one of the forms <input> elements.
You can probably ditch the input.addEventListener("keyup", function(event) {...} altogether by just using the obsubmit handler.
You can learn more about the HTML <form> element's onsubmit behavior here:
https://www.w3schools.com/tags/ev_onsubmit.asp
No need to put handlers on button element. You should use either input type as submit or button type as submit. onsubmit handler can be given to form element where you can actually prevent default event and go ahead with password validation .
Hope this gives you an idea.
If I were you, I would do two things:
1) I would check the Chrome debugger to see if there are any issues with your code
2) Instead of input.addEventListener("keyup", function(event) {, I would try input.onkeyup = function(event) { and see if that works.
Hope this helps.
Have been searching for a solution to this problem for 2 days now and none of the suggested solutions have worked so far.
My form html is defined with
<form id="quote_form" action="" method="get" class="ui large form">
and input text fields in the form
<input v-model="city" type="text" name="quote[city]" id="city">
I have been trying to isolate the cause of the issue but have not been able to do so. I tried turning off the keyboard shortcuts settings for semantic ui forms:
$('.ui.form').form({
keyboardShortcuts: false
});
I have also tried to override the enter key and prevent it from triggering the submit function in these ways:
$('#quote_form').on('keyup keypress', function(e) {
var keyCode = e.keyCode || e.which;
if (keyCode === 13) {
e.stopPropagation();
e.preventDefault();
return false;
}
});
$(document).on("keypress", "form", function(event) {
return event.keyCode != 13;
});
$('#quote_form').bind('keypress keydown keyup', function(e){
if(e.keyCode == 13) { e.preventDefault(); }
});
The form has multiple steps in filling it in. Each step uses a button to permit the advance to the next step. When enter is pressed then it causes the form to redirect to the first step/tab of the form. The only case where it doesn't redirect is when the rules of the current step are not satisfied. The form submission is handled by a submit button where the button itself calls methods to validate and submit the form. I can't find any connection between enter submit behaviour and the button for submitting.
If I am missing any useful information to help isolate the cause then please let me know. I'm new to asking questions here and want to prevent my question from being considered bad as much as possible :)
Here is solution for you:
#submit.prevent
https://jsfiddle.net/4qpffycs/2/
Just use #keyup.enter.prevent at the end of the input markup. See VueJS Doc
By the way, you should try to use native VueJS Events instead of all redoing it with JQuery
The solution I found regards only Semantic UI without VueJS, but should be applicable here and gives a bit of an insight into the issue.
The problem arises from the fact that $("#formId").form({ ... }) registers an event handler for a button press and submitting the form on Enter press if one of the input boxes are selected. This can be seen in Chrome DevTools when selecting the element and choosing Event Listeners category:
The simplest way I found to remove this behavior is to call
$("#formId").unbind('keydown')
to remove the keydown bind completely from the element.
I've got the following problem:
I use bootstrap form to take input from users, and I use jQuery preventDefault() to disable the submit button from sending the form (I use AJAX instead). However, that function also prevents input checking that is done by bootstrap. For example, if someone enters an e-mail without '#' into
<input type="email" class="form-control">
bootstrap would, upon clicking submit, check that input and return a popup with an error.
My question is: how to prevent the request being sent while keeping the bootstrap form checking mechanism intact?
What I have tried: using preventDefault() and writing my own checking script, however this seems like reinventing the wheel and having extra code when it's not needed.
Thank you!
I believe you are talking about the native HTML5 form validation and not validation by bootstrap its self, I have never come across bootstrap validation before. (i may be wrong though).
Most new browsers will validate <input type='email'/> as an email address and <input type='text' required='required'/> as required on form submission.
If for example you are using e.preventDefault(); on the click event on the submit button the form will never attempt to submit and hence the native validation will never happen.
If you want to keep the validation you need to use e.preventDefault(); on the submit event of the form not the click event on the button.
The html...
<form action='' method='post'>
<input type='email' name='email' required='required' placeholder='email'/>
<button type='submit'>Submit</button>
</form>
The jQuery...
//this will stop the click on the button and will not trigger validation as the submit event will never be triggered
$("button").on('click',function(e){
e.preventDefault();
//ajax code here
});
//this will stop the submit of the form but allow the native HTML5 validation (which is what i believe you are after)
$("form").on('submit',function(e){
e.preventDefault();
//ajax code here
});
Anyway hope this helps. If I have misunderstood in any way let me know and ill try to assist further.
I had the same issue, I came to use "stopPropagation" as the way to stop the form submission. But after a little reading on jQuery 3, I realized that "preventDefault" was enough to what I wanted.
This caused the form validation to happen and the submit event didn't proceed.
(This example is of an attempt i had on my own).
$('form').on("submit",function( event ) {
if ( $('#id_inputBox_username').val().length == 0 &&
$('#id_inputBox_password').val().length == 0 ) {
event.preventDefault();
$('#id_inputBox_username').tooltip('show');
$('#id_inputBox_password').tooltip('show');
} else if ( $('#id_inputBox_username').val().length == 0 ) {
event.stopPropagation();
$('#id_inputBox_username').tooltip('show');
} else if ( $('#id_inputBox_password').val().length == 0 ) {
event.stopPropagation();
$('#id_inputBox_password').tooltip('show');
}
});
I had the same problem and I find this solution:
$('#formulario').on('submit', function (e) {
if (e.isDefaultPrevented()) {
// handle the invalid form...
} else {
// everything looks good!
e.preventDefault(); //prevent submit
$(".imprimir").show();
$(".informacao").fadeOut();
carregardados();
}
})
I have an HTML input text field.
How can I perform a specific JavaScript call when hitting "Enter" button while editing that field? Currently, hitting "Enter" reloads the entire page, presumably due to submitting the entire form.
NOTE: This HTML/JS code is merely included as a portlet into a large HTML page for a portal, which has one large master form wrapped all the way around my code. Therefore I can not control the form - can't change onSubmit event or action or wrap my INPUT field into a smaller form - otherwise the solution would be obvious :)
Also, a solution that does not involve adding a visible button to the form is strongly preferable (I don't mind adding a button with display:hidden if that's what it takes, but my attempt to do so didn't seem to work).
This needs to be straight up JS - no Query/Prototype/YUI is available.
P.S. it's a search field and the action will be a call to an existing in-page JavaScript search method, if someone's curious.
Thanks!
Assuming you have a text input something like
<input id="myTextBox" name="foo" value="bar">
... you could do something like this, after the document has loaded, and it will work in all mainstream browsers:
document.getElementById("myTextBox").onkeypress = function(evt) {
evt = evt || window.event;
var charCode = evt.keyCode || evt.which;
if (charCode == 13) {
// Suppress default action of the keypress
if (evt.preventDefault) {
evt.preventDefault();
}
evt.returnValue = false;
// Do stuff here
}
};
Include the following javascript
<script type="text/javascript">
function noenter() {
return !(window.event && window.event.keyCode == 13);
}
</script>
Add the following attribute into the input element that you wish to prevent the submit
onkeypress="return noenter()"
Of course you can perform some other event if you wish...
Would you be better off using the document object to detect the Enter action? That way you need make no changes to the HTML form tags. You can assign the search function to the button, although if it's hidden I am not sure how the user would click on it, or you could use something like onblur to capture the user tabbing out of the input control.
Try adding an attribute "action=javascript:void(0)" as in the example below.
Enter will trigger the same action as clicking on the submit button, but won't reload the page automatically.
<html>
<head></head>
<body>
<div id="status"></div>
<form action="javascript:void(0)">
<input type="text" />
<input type="submit" value="submit" onclick="document.getElementById('status').innerHTML = 'submitted';"/>
</form>
<script>document.getElementById('status').innerHTML = 'page loaded';</script>
</body>
</html>
I have noticed a rather strange behaviour in IE.
I have a HTML form with a single input text field and a submit button
On Submit click I need to execute a client side JavaScript function that does the necessary.
Now when I want to prevent the postback in the text field (on enter key press).
I have added a key press JavaScript function that looks like this:
<input type=text onkeypress="return OnEnterKeyPress(event)" />
function OnEnterKeyPress(event) {
var keyNum = 0;
if (window.event) // IE
{
keyNum = event.keyCode;
}
else if (event.which) // Netscape/Firefox/Opera
{
keyNum = event.which;
}
else return true;
if (keyNum == 13) // Enter Key pressed, then start search, else do nothing.
{
OnButtonClick();
return false;
}
else
return true;
}
Strangly this doesn't work.
But if I pass the text field to the function :
<input type=text onkeypress="return OnEnterKeyPress(this,event);" />
function OnEnterKeyPress(thisForm,event) {
var keyNum = 0;
if (window.event) // IE
{
keyNum = event.keyCode;
}
else if (event.which) // Netscape/Firefox/Opera
{
keyNum = event.which;
}
else return true;
if (keyNum == 13) // Enter Key pressed, then start search, else do nothing.
{
OnButtonClick();
return false;
}
else
return true;
}
I am able to prevent the postback.
Can anyone confirm what is exactly happening here?
The HTML form has just one text box and a submit button.
The resultant output of the JavaScript function executed on submit is displayed in a HTML text area in a separate div.
Found out a work around for this issue.
i just found out that in IE, if,in a form, there is just one text field and one submit button, pressing enter results in form submit. However if there are more than one text boxes, IE doesn't auto postback the form on enter press, instead it fires the button's onclick event.
So i introduce a hidden text field in the form and everything works magically.
I donot even need to handle the onkeypress event for the text field.
<Form>
<input type="text" />
<input type="text" style="display:none"/>
<input type="submit" onClick="callPageMethod();return false;"/>
</Form>
This works perfectly for me!!
This is not an issue in FF, as pressing enter directly results in call to submit button's onclick event.
Hi you can also disable the default behavior.
jQuery('#yourInput').keydown(function (e) {
if (e.keyCode == 13) {
e.preventDefault();
}
});
Cheers!
Return false in the onsubmit which is used to submit the form via javascript.
There must be some interaction with other code you haven't posted. Your code stops the form submission for me in both variants and there is no reason it shouldn't.
But trapping Enter keypresses is difficult to do properly and is likely to annoy as much as anything else. There is almost always a better way.
For example, as altCognito suggests, have ‘form.onsubmit’ return false so the form never submits in response to user interaction. Also, if you put your AJAX code (assuming that's what you're doing) in the onsubmit handler instead of onclick on a button, you can also make it so that pressing Enter has the same effect as clicking on the submit button, which the user might normally expect.
If you don't want that, there seems to be no reason to include the <form> element at all. It's perfectly valid to just have input elements sitting on their own, if you never expect the browser to submit them anywhere.
Have just come here because of a related observation with at least IE 7 and 8:
If there is only one text input and one submit button on a form and the user presses return key, IE will not include the submit button's name/value-pair in the request. Insead, only the text input's value will be there.
If I add another text input, both text inputs and the submit button's parameters are posted. The second text input can even be hidden: <input type="text" style="display:none"/>
So this is not related to events but rather to simple form submission.
It happens with GET and POST. Adding a select element to the form does not change the behavior. -- very strange.