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.
Related
I have the "chips" form link you can see in the attached image here and I want to create a condition such as if someone press "Enter" he can note the item added but what happens here is that form sends the data to backend.
I tried many times to modify the behavior using the "event" but it didn't work you can see the approaches I sticked with:
Approach1:
// input to submit job
const submit_job = document.getElementById("submit-job");
submit_job.onclick = (e) => {
e.preventDefault();
if (e.key !== "") {
console.log(e.currentTarget)
} else if (e.pointerType === "mouse") {
submit_job.onsubmit = () => {
return true
}
}
}
// This approach won't work because I found that "e.key" worked only when typing by Keyboard
Approach 2:
function getEventType(event) {
if (event.type === "keydown") {
event.preventDefault();
}
}
submit_job.addEventListener('keydown', getEventType, true);
submit_job.addEventListener('click', getEventType);
so, any help in that issue, please?
Note:
No need to see the full code because the code is working fine but when I place it into the form this problem occurs so, you can spire me using that variable only "submit_job" in your answer.
Your implementation of the form submission does not seem like a good idea. You should not prevent users from submitting the from when pressing "Enter". Clicking "Enter" should trigger a form submission which is common for most forms. Why not add a unique button beside the input field that when clicked allows the user to enter a note or text? If you take your current approach users will only be able to submit by clicking the submit button which is bad practice. I suggest creating an additional button and adding an event handler to that button so you have a button that adds notes when clicked, so pressing "Enter" will not clash with what you are trying to accomplish.
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.
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 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).
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>