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.
- You haven’t setup your event listeners on your form
- You’re checking if the variables
nameandemailare empty strings instead of checkingname.valueandemail.valueare empty strings.nameandemailare HTML Elements, to check their value you must check.value - You’re not checking if the
.valueof each are null - 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/