Why isn't this Javascript function showing the alert()?

Issue

I’ve got a function to show an alert if two elements aren’t filled out, but the alert isn’t showing up and it’s just reloading the page. Not sure what I’ve missed or where I’m going wrong.
Here is the Javascript:

function submitNewsletter() {
    var name = document.getElementById("name");
    var email = document.getElementById("email");
    if (name == "" || email == "") {
        alert("Please fill in your details.");
        return false;
    }
}

And here is the html it’s for:

<section class="signup">
        <h1>Keep up to date.</h1>
        <p>Sign up to our newsletter to hear about improvements and additions to Electric Dreams.</p>
        <form class="newsletterForm">
            <label for="name" class="label">Full Name</label>
            <input type="text" id="name" name="name" class="input" placeholder="Full Name"> <br>
            <label for="email" class="label">Email Address</label>
            <input type="email" id="email" name="email" class="inout" placeholder="Email Address"> <br>
            <button type="submit" class="btn" onclick="submitNewsletter()">Submit</button>
        </form>
    </section>

Solution

There’s a few reasons why this code does not work.

  1. You haven’t setup your event listeners on your form
  2. You’re checking if the variables name and email are empty strings instead of checking name.value and email.value are empty strings. name and email are HTML Elements, to check their value you must check .value
  3. You’re not checking if the .value of each are null
  4. You must call event.preventDefault() in your form’s submit callback function. Otherwise the form’s submit will cause the page to reload.

Here’s the code revised to work:

function submitNewsletter(event) {
    event.preventDefault();
    var name = document.getElementById("name");
    var email = document.getElementById("email");
    if (name.value === "" || email.value === "" || !name.value || !email.value) {
        alert("Please fill in your details.");
        return false;
    }
}

document.querySelector(".newsletterForm")
    .addEventListener('submit', submitNewsletter);

JSFiddle: https://jsfiddle.net/qu2pesw0/1/

Answered By – Ian

Answer Checked By – Jay B. (AngularFixing Admin)

Leave a Reply

Your email address will not be published.