I am super new to coding and having a difficult time with some of the logic. I asked another question last night and the community was really helpful (Thanks!), so I thought I'd try it again. `
I am trying to make an program that collects the user's email and first name. I want to check that there is something entered in each of the boxes on the form and, in order to ensure they entered their email address correctly, that emailAddress1 is the same as emailAddress2.
I have defined a "var errorMessage = "";" and if there is error at any point, it redefines a new errorMessage based on the mistake the user made on the form.
The problem, I think is with the second if-else statement. I thought that if the "errorMessage = "";" still, it would submit the form. However, no matter what it's executing the else statement and I'm getting an alert of an empty error message.
Why, if errorMessage = "", is it running the else statement and skipping over the if statement that uses errorMessage = "" as the condition?
"use strict";
var $ = function(id) {
return document.getElementById(id);
};
var joinList = function() {
var emailAddress1 = $("email_address1").value;
var emailAddress2 = $("email_address2").value;
var firstName = $("first_name").value;
var errorMessage = "";
// validate the entries
if (emailAddress1 == "") {
errorMessage = "First email address entry required";
$("email_address1").focus();
} else if (emailAddress2 == "") {
errorMessage = "Second email address entry required";
$("email_address2").focus();
} else if (emailAddress2 != emailAddress1) {
errorMessage = "Email address entries must match";
$("email_address2").focus();
} else if (firstName == "") {
errorMessage = "First name entry required";
$("first_name").focus();
}
// submit the form if all entries are valid
// otherwise, display an error message
if (errorMessage = "") {
$("email_form").submit();
} else {
alert(errorMessage);
}
};
window.onload = function() {
$("join_list").onclick = joinList;
$("email_address1").focus();
};
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title> Join Email List</title>
<link rel="stylesheet" href="email_list.css">
<script src="email_list.js"></script>
</head>
<body>
<main>
<h1>Please join our email list</h1>
<form id="email_form" name="email_form" action="join.html" method="get">
<label for="email_address1">Email Address:</label>
<input type="text" id="email_address1" name="email_address1"><br>
<label for="email_address2">Re-enter Email Address:</label>
<input type="text" id="email_address2" name="email_address2"><br>
<label for="first_name">First Name</label>
<input type="text" id="first_name" name="first_name"><br>
<label> </label>
<input type="button" id="join_list" value="Join our List">
</form>
</main>
</body>
</html>
**