function wvalidateForm(){
var guestName = document.forms["wcoform"]["guestname"];
if (guestName == "") {
var werrorMessage = document.getElementsByClassName("werrormsg");
werrorMessage.innerHTML = "No";
}
}
The submitHandler function is where you prevent the default action of the form, get information from the event object if need be, and pass execution on to another function to do the actual work.
function submitHandler(evt) {
const form = evt.target;
evt.preventDefault();
validateForm(form);
}
And from there, the validateForm function receives a reference to the form, letting you easily do what needs to be done.
function validateForm(form) {
...
}
If validation is successful you can then call form.submit() to submit the form, and as it’s being called from within JavaScript, it won’t trigger the submit event once again.
Ajax just means that you don’t get to immediately figure out if things are valid, and have to wait for another server somewhere else to do that instead.
None of that though changes any of the above process either.
Only the onsubmit part is to be removed. A way of gaining access to the form is required, which the identifier achieves well. The rest of what you had doesn’t need to change.
[quote=“codeispoetry, post:9, topic:337823, full:true”]
even if any one validations fails - No submission, but when validations will be true. How can we instruct the form to be submitted?[/quote]
When the validation is true, that’s when you call form.submit();
A typical way of doing this is to start with isValid being true, then check for things that need to be correct. Anything that’s not correct sets isValid to be false.
var isValid = true;
if (...) {
// show error message
...
// and then
isValid = false;
}
if (...) {
// show another error
...
// and then
isValid = false;
}
// and finally
if (isValid) {
form.submit();
}
Only if isValid remains true will the form be submitted.
Got it. I now have logical clarity to write something. I will get back to you once done or in any issue. Thanks for the guidance. You are wonderful sir. Thank you so much.
one last question for now →
var isValid = true; This to be inside any function?
It’s best to keep it inside of the validate function. If anything needs information about what happened, that’s usually achieved by returning information from the function.
You’re defining the same variable in line 1 - why not make use of that? Also, with this setup, you’re not making use of the form variable you’re passing onto wvalidateForm() so what’s the point ?
Look at this line very closely - it’s causing a syntax error.
Edit - then all you have to do is realize that the getElementsByClassName returns a node list, and you need to target the right error message to populate the message.