I need to verify the email fields are the same before submitting the form.
I have submitted the full html in the codepen with comments below but I am most unsure about the function and the syntax of how to prevent the form from submitting and alerting the user to make sure the emails match.
I tried the following code, I expected the browser to send an alert to the user that they need to "make sure the emails match" if they input emails that are different, what resulted was when submitting the form and the emails don’t match it does not alert the user and prevent the form from submitting
const element = document.getElementById("submit");
element.addEventListener("click", checkEmail);
function checkEmail() {
const email = document.getElementById("first");
const confirm = document.getElementById("confirm");
if (email === confirm) {
document.getElementById("form").submit();
} else {
event.preventDefault();
alert("Make sure the emails match");
}
}
<form action="http://northcarolinatest.atwebpages.com/Form.html" method="POST" id="form" autocomplete="off">
<label for="first">First Name:</label>
<input type="text" name="first" id="first" placeholder="John" required>
<br>
<label for="last">Last Name:</label>
<input type="text" name="last" id="last" placeholder="Doe" required>
<br>
<label for="email">Email Address:</label>
<input type="email" name="email" id="email" placeholder="[email protected]" required>
<br>
<label for="confirm">Confirm Email:</label>
<input type="email" name="confirm" id="confirm" placeholder="[email protected]" required>
<br>
<label for="question">Question:</label>
<input type="text" name="question" id="question" placeholder="Where do I go to register to vote?" width="500px" required>
<br>
<input type="Submit">
</form>
3
Answers
What you need to do is intercept the
submit
event of<form>
, not some strange button:If you want to use standard HTML5 form usage…
As @Đinh Carabus said, you are comparing two elements denoted by these:
You must get their values first before you compare them lest, a mismatch will happen.
You also need to intercept the form’s submit event as @Tachibana Shin said.
Here’s what your JS code should be: