I want to know if submit gets called if my form data are not valid in html5 validation. For example I have a form id personal_info.
I use the following block to get on submit event :
$("#personal_info").submit(function(event) {
event.preventDefault();
saveData("personal_info");
});
function saveData(formName){
console.log("test");
}
Is is the default behavior that the function saveData gets called on submit because even if my form is not valid the function gets called.
How to prevent submit function from being called if my form is invalid?
The new HTML5 validation APIs will not submit an invalid form unless you use the novalidation attribute on the form. See https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Forms/Data_form_validation for more information.
It works but should on submit be called if the form is not valid.
Anytime your form #personal_info is submitted, the submit function will run.
The reason it may appear that the submit function isn't running, is because of this line
event.preventDefault();
This prevents the default action from taking place, which is submitting the form. So the form won't submit normally, thus your web page won't reload/refresh.
Calling submit even if the form is not valid, is just fine. Nothing wrong with that. The way your code is in your question, the saveData function is set to run each time, even if it's not valid. So we can change that from happening.
Like A. Wolff said in the comments, you could just wrap an if statement around your call to saveData function.
So you could have your code look something like this
$("#personal_info").submit(function(event) {
event.preventDefault();
if ($(this).valid()) { // if form is valid
saveData("personal_info"); // then do this
}
});
function saveData(formName){
console.log("test");
}
Related
I need to validate a form before it can be submitted. I'm following the pretty standard procedure of adding event listener to the form's submit event, canceling the default behavior, and then once everything has been validated, submitting the form through submit() method after removing the event listener. But for some reason, the event doesn't get removed and the page keeps on reloading. Here is my code:
// Prevent form submission on button click and validate form input fields first
cartForm.addEventListener('submit', validateInputFields);
function validateInputFields(event) {
event.preventDefault();
validateName();
validateRecipientPhone();
validateCustomerPhone();
validateAddress(submitForm);
}
function submitForm() {
// remove validation event listener and submit form
cartForm.removeEventListener('submit', validateInputFields);
cartForm.submit();
}
Here validateAddress makes an async API call and takes some time to resolve therefore I passed submitForm as callback which can be triggered once validateAddress resolves. Does this have something to do with my form not getting submitted? Or am I making some other mistake? It's stuck in a loop no matter address gets validated or not.
The first three validation functions are only checking if fields are populated and have correct lengths.
How can I work around this issue?
i have ajax validation function and when ajax validation is true then i use:
$("#test_form").submit();
it is work fine but any time i can click Enter and submit a form when form is not validated (skip validation process and pass wrong data).
i try put
$("#test_form").submit(function(){event.preventDefault();});
then still can submit with enter when data is wrong
or
$("#sample_form").submit(function(){false});
then i cant submit any time.
How to submit only when ajax is true?
The first part of your answer is said in the comment section :
Use $("#test_form").submit(function(event){event.preventDefault();}); notice function(event)
– Satpal
Then you'll notice an other problem, your form will never submit after the AJAX call. That is because you use $("#test_form").submit(); to submit, which is the jQuery triggering the event. When jQuery trigger the event, it will always be prevented by the preventDefault.
What you need to do is to use the native JavaScript event :
$("#test_form")[0].submit();
When you are using the native handler, the event you have been added with jQuery will not trigger. It will instead directly send the form.
In Submit button, Use onclick with return then On press enter it will check first javascript validation.
I'm wondering what exactly the return false; statement is doing in this Pig-Latin translator? By removing it I can see that the page seems to automatically refresh (immediately wipes the 'translation' rather than leaving it), but I don't understand the mechanics. What's going on? I don't think the HTML or JS is necessary to answer my question, but let me know if I'm mistaken and I'll paste it in.
The jQuery:
$(function() {
$("form#translator").submit(function() {
var englishWord = $("input#word").val();
var translatedWord = englishToPigLatin(englishWord);
$("#english").append(englishWord);
$("#pig-latin").append(translatedWord);
$("#translation").show();
return false;
});
});
From the .submit documentation (emphasis mine):
Now when the form is submitted, the message is alerted. This happens prior to the actual submission, so we can cancel the submit action by calling .preventDefault() on the event object or by returning false from our handler.
So, returning false prevents the default action (in this case form submission), but also stops the propagation of the event. It is equivalent to calling event.preventDefault() and event.stopPropagation().
It seems like you don't know how forms are processed:
When a form is submitted, the browser is making a GET or POST request to the URL provided in the form's action attribute, i.e. it will load that URL. If no action attribute is provided, the request will be made to the current URL, which effectively reloads the page (but also sends data to the server).
For more information, see MDN - Sending and retrieving form data.
You are executing the function when the form is being submitted. By returning false you effectively disable the form submit so the page won't get submitted to the server.
If you do submit to the server, the server will return the new page and your javascript changes will indeed be gone until you click the submit button again.
Alternatively you could use this instead of return false:
your_form.submit(function(e){
e.preventDefault();
});
Versus:
your_form.submit(function(e){
return false;
});
by "return false" , the form will executed, but your page will not reload / refresh.
for whatever reason my code won't redirect to another file after I press submit.
$('form').submit(function () {
window.location.replace('test.html'); });
I have defined everything in an html file. Any ideas?
Thanks,
busterroni
You need to stop the form from submitting. That can be done by calling preventDefault() on the event object that is passed in.
$('form').submit(function (e) {
e.preventDefault();
window.location.replace('test.html');
});
Not cancelling the form submission, you created a race condition. You had the form submitting back to the current page and you had the location trying to navigate away.
If you want the back button to work, you probably want to use assign() and not replace().
I'm working on an HTML form that may take a few seconds to submit. I'd like to disable some of the fields in the form after it's submitted.
I can do this in a handler on the form's submit event, but this fires before the form submits. If I disable the controls then, their values aren't included in the post data sent to the server.
I've tried cancelling the submit event in my handler, removing my submit event handler from the form, submitting the form myself via JavaScript, and then disabling the controls, but the problem there is that I need to know which button the user clicked on to submit the form. This information is in the original form submit, but obviously isn't in the one I trigger manually (as no button was clicked).
I could try to copy this information into my manual form submit, but is there a way to run my disabling code after the form submits?
Don't allow further submits by disabling the submit buttons, you don't need to do anything else. Alternatively, hide the form and replace it with something that spins so users are mesmerized into thinking that Something Important is happening.
This is pretty much the same as sp00m's answer, except it uses Javascripts native submit to prevent the recursive call.
$('#myForm').submit(function() {
this.submit();
disableFields(); // your own function
return false;
});
After submiting the form you can trigger this function:
function name() {
$("#target :input").attr("disabled", true);
return true;
}
This code will disable all the from fields descended from the element with "target" as its id.
This version just matches all input elements:
function name() {
$("#target input").attr("disabled", true);
return true;
}
You have to include the jQuery library for this code to work.
You could use jQuery's .post() to submit, and .button().click() to detect what button was clicked
.post() takes a function to execute after the submission is complete
You could delay the execution of your operations so that they are called only after the submit has been made:
$('#myForm').submit(function() {
setTimeout(function() {
// Run disabling code here
}, 1);
return true;
}
setTimeout(fn, 1) will place the function inside at the end of the execution queue, so that the form submission has been started before the functions run.
setTimeout can be used for queuing operations a bit like thread indexing or z-index:
StackOverflow: Why is setTimeout(fn, 0) sometimes useful?