I’m working on an assignment for school and it’s asking me to create an alert for two email addresses being different. What I have works as far as giving an alert when the two emails are different, except that it gives an alert in any other case as well. How do I fix this? Here’s what I got:
function alertBox() {
let email = document.getElementById("email");
let confirmation = document.getElementById("confirmation");
if (email != confirmation) {
alert("Email addresses do not match. Please try again.");
}
}
<form method="POST">
<p>
<label for="email">Email Address:</label>
<input type="text" name="email" id="email">
</p>
<p>
<label for="confirmation">Confirm Email:</label>
<input type="text" name="confirmation" id="confirmation">
</p>
<p>
<textarea placeholder="Ask question here" id="textarea"></textarea>
</p>
</form>
<button onclick="alertBox()">Submit</button>
The assignment says to create a "submit" button and that the form isn’t supposed to be submitted to a server, hence no action attribute in the form element and a button instead of input type submit. Any help is appreciated.
2
Answers
compare the
.value
of the input element instead of the element referenceYou can use the build-in form validation for this. Set the
required
attribute on the input elements. Each time the input event happens on the email form field, the pattern of the confirmation form field is updated to have the same value. So, the form will only submit if the confirmation form field has the same value as the pattern aka. the email form field.On invalid events the class name of the form field is changed to "invalid". This displays a stop sign. On input events, if the form field is valid, the class name will change to "valid", and the check mark will show.