Probably a very easy fix for you JS gurus out there, currently I have a form with some basic validation. If i call it outside of a submit function it works fine, however i need the form to submit once it checks the validation, can anyone help? Also is the correct way to call it by returning true at the bottom of the function?
function submitForm() {
//Form validation, post.
submitBtn.addEventListener("click", function(event) {
event.preventDefault();
//Form fields
const contactName = document.getElementById("form__contact-name").value;
const contactEmail = document.getElementById("form__contact-email").value;
const contactPhone = document.getElementById("form__contact-phone").value;
const contactMessage = document.getElementById("form__contact-message").value;
//Check if values aren't empty, if they're not post form. Else alert the user to complete.
contactName !== '' && contactEmail !== '' && contactPhone !== '' && contactMessage !== '' ?
true :
alert("Please complete form");
})
}
<form action="#" method="post">
<div class="form__contact-wrapper">
<label for="Your name">Your Name</label>
<input id="form__contact-name" type="text" name="contact-name" />
</div>
<div class="form__contact-wrapper">
<label for="Your email">Your email address</label>
<input id="form__contact-email" type="text" />
</div>
<div class="form__contact-wrapper">
<label for="Your phone number">Your phone number</label>
<input id="form__contact-phone" type="number" />
</div>
<div class="form__contact-wrapper">
<label for="Your message">Your message</label>
<textarea id="form__contact-message" rows="5"></textarea>
</div>
<div class="form__contact-wrapper">
<input id="submitbtn" type="submit" value="send my message" onsubmit="submitForm()" />
</div>
</form>