My CS teacher insists that all JS has to be put in the <head>
tags and nowhere else. He also insists that we use only vanilla javascript without any libraries. So in an effort to comply, I've created the following form with accompanying JS to validate it. The problem is that when wrapped in the state change checker it doesn't work. My code is below
HTML
<!DOCTYPE html>
<html>
<head>
<script src="script.js"></script>
</head>
<body align="center">
<h2>Super Secret Login</h2>
<!--Added an onsubmit action to catch the form in case it isn't valid !-->
<form onsubmit="return j.validate()" name="myForm" action="http://sophist.cs.slcc.edu/~philn/cgi-bin/quick.cgi" method="post">UserID:
<input name="userid" size="15" /> <!-- Remember closing tags on all elements !-->
<br />
<br />Password:
<input name="password" size="15" />
<br />
<br />
<center>
<table cellspacing="20px">
<tr>
<td align="left">
<input id="submit" type="submit" value="Submit" />
</td>
<td align="right">
<input type="reset" value="Clear" />
</td>
</tr>
</table>
</center>
</form>
</body>
</html>
JavaScript
function domReady() {
var flag;
var userid = document.myForm.userid;
var pas = document.myForm.password;
this.validate = function () {
if (userid.value === "milton1" && pas.value === "k1mb3r")
{
flag = 1;
} else if (userid.value === "shelly15" && pas === "4ng21") {
flag = 1;
} else {
flag = 0;
}
if (flag === 0) {
alert('There was a problem with your username and password');
return false;
} else {
return true;
}
};
}
// Mozilla, Opera, Webkit
if (document.addEventListener) {
document.addEventListener("DOMContentLoaded", function () {
document.removeEventListener("DOMContentLoaded", arguments.callee, false);
var j = new domReady();
}, false);
// If IE event model is used
} else if (document.attachEvent) {
// ensure firing before onload
document.attachEvent("onreadystatechange", function () {
if (document.readyState === "complete") {
document.detachEvent("onreadystatechange", arguments.callee);
var j = new domReady();
}
});
}
Now without wrapping the whole thing in a function and calling the submit as a method this works, so long as I put the script at the bottom of the page. Can someone help me understand why it does not work in this way?