I'm currently working on a task where I need to validate a form and display a message that says 'Please complete the form!' Everything seems to be functioning correctly except for the message. What could I be missing here? How can I make this work or is there something simple that I am overlooking? I've experimented with placing the script at the top and bottom, but prefer it at the bottom to ensure the page loads quickly without any interruptions from JavaScript.
<!DOCTYPE html>
<html lang="en>
<head>
<meta charset="utf-8">
<title>Index</title>
<!--[if IE 9]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<link rel="stylesheet" href="styles.css">
</head>
<body>
<form action="login.php" method="post" id="loginForm">
<fieldset>
<legend>Login</legend>
<div><label for="email">Email Address</label>
<input type="email" name="email" id="email" required></div>
<div><label for="password">Password</label>
<input type="password" name="password" id="password" required></div>
<div><label for="submit"></label><input type="submit" value="Login →" id="submit"></div>
</fieldset>
</form>
<script src="login.js"></script>
</body>
</html>
JavaScript code:
function validateForm() {
'use strict';
var email = document.getElementById('email');
var password = document.getElementById('password');
if ( (email.value.length > 0) && (password.value.length > 0) ) {
return true;
} else {
alert('Please complete the form!');
return false;
}
}
function init() {
'use strict';
if (document && document.getElementById) {
var loginForm = document.getElementById('loginForm');
loginForm.onsubmit = validateForm;
}
}
window.onload = init;