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();
}
})
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.
I have a form which is producing a lot of spam. I have made all inputs required and have attached a captcha. This has not had any affect.
I assume the bots are using form.submit() as for some reason this bypasses all my required fields AND also bypasses my onsubmit="check(e)"
I cannot seem to grab this event .submit() by any means. Does anyone know how to catch this event and make sure it is cancelled. I want the only way to submit the form is through clicking the submit button.
$("#myForm").submit(function(event) {
console.log("Handler for .submit() called.");
if (CaptchaInput.value == "") {
event.preventDefault();
}
});
My code that was supposed to catch a .submit() call and prevent the form submission. This function is never triggered.
<form target="hidden_iframe"
onsubmit="if (CaptchaInput.value == '') { why += '- Please Enter CAPTCHA Code.\n'; alert(why); return false; };return checkform(this)" id="myForm">
You cannot. I can submit your form without a browser, or with JavaScript disabled. Anyone can just send an HTTP POST request to your server, without going through any client-side process you may introduce.
The solution to your problem is to also verify on the server, and don't rely on the client side validation to have completed successfully (or indeed, even to have been run at all).
Treat client-side validation as a convenience to your users, they see the error immediately without having to retype and resubmit the entire form.
You can define the onsubmit attribute of the form, to run a function that validates your input. The browser will submit the form only if that function returns true.
UPDATE:
You can define the action only after the form has been validated.
So, your html will look something like this:
<form id="myForm" onsubmit="return checkRecaptcha()" action="disabled">
<input type="text" name="myTextInput" value="">
<input type="submit" value="Submit">
</form>
And your javascript code, that defines the function will look like this:
function checkRecaptcha() {
if (CaptchaInput.value == "") {
document.getElementById("myForm").action="myCorrectUrl";
return true;
} else {
alert("not allowed");
return false;
}
}
Then for catching the submit function:
document.getElementById("myForm").submit = function () {
console.log("catched");
return false;
}
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 prefer submitting form values with AJAX by hitting "Return" and all my setups, which I did before, are working, but today it stopped working. Here are the the steps, which I have been following for a quite a long time.
Include jQuery
Setup my form
Preventing it form submitting
$(document).ready(function(){
$(document).on('keyup', myFormSelector, function(event){
if ( event.keyCode === 13 ) {
event.preventDefault();
}
});
});
change the event to keydown and it will work.
try to disable the default behaviour from the submit event and add a SUBMIT-element (display:none).
If a form does have a submit-element, the return key does work like you want it.
Howto disable the submit event:
$('#myForm').submit(function(e) {
e.preventDefault(); // disabling default submit with reload.
// ajax code here
});
if this does not work, u may try this also:
<form id="myForm" onsubmit="return false"> ... </form>
Returning false does stop submitting too.
When using submit elements instead of keyup/keydown, you will be able to add multiple forms on your page with the desired behaviour.
I have function that submitted two forms at once. And last (the second) post method does not take effect without alert().
Could you please show me my mistake.
function formFunction() {
...
$.post($("#form1").attr("action"), $("#form1").serialize() );
$.post($("#form2").attr("action"), $("#form2").serialize() );
//alert('done');
}
UPD
this is how function is calling
<form id="form0" name="form0" onsubmit="formFunction()">
<input id="mainFormValue" type="text">
The reason why it is failing is you are not cancelling the original form submission. That means the page is posting back to the server when you click the button. What you need to do is prevent that origial form submission from completing.
If you are adding the event handler with jQuery, you can use preventDefault() to cancel the form submission.
function formFunction(e) {
e.preventDefault();
$.post($("#form1").attr("action"), $("#form1").serialize() );
$.post($("#form2").attr("action"), $("#form2").serialize() );
}
Change the form submission to unobtrusive JavaScript to get the correct event object set by jQuery.
$("#form0").submit(formFunction);
The other solutions is add a return false to the submisison. Just ignore the preventDefault line I suggested above. [bad idea, but will work]
<form id="form0" name="form0" onsubmit="formFunction(); return false">