Okay so my code pretty much works… except if you click submit a second time and there is STILL a field empty, the appended * required in the label tags before the input tags will become duplicated. This is bad! I am able to alert the nodeValue after function(x), yet somehow there is an issue with alerting anywhere else… which also, I believe, is the reason I cannot use the simple if statement solution I have commented out at the bottom of my code.
Any revisions to my code or suggestions will be greatly appreciated. Alternatively, I’d love some links to follow. Hopefully one day I can think programmatic enough to give back on SO…
Thanks so much in advance. Here is my code:
Javascript:
var obj = {
form : document.getElementsByTagName('input'),
btn : document.getElementById('submit'),
init : function(){
obj.btn.form.onsubmit = obj.handleEvent;
},
handleEvent : function(){
for (var i=0; i<obj.form.length; i++){
if (obj.form[i].value===''){
switch(obj.form[i].name){
case 'fname' :
case 'lname' :
case 'phone' :
case 'email' : match=true; obj.error(obj.form[i]); break;
}
}
}
return false;
},
error : function(x) {
var req = document.createTextNode(' * required');
var span = x.previousSibling.appendChild(document.createElement('span'));
span.className = 'error';
// if (x.previousSibling.firstChild.nextSibling.firstChild.nodeValue !== ' * required'){
span.appendChild(req);
// }
// alert(x.previousSibling.firstChild.nextSibling.firstChild.nodeValue);
}
}
and the HTML:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<link type="text/css" href="css/main.css" rel="stylesheet" />
<head>
<title>JavaScript Input form</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<form method="post" action="">
<div>
<ul>
<li><label>First Name</label><input type="text" name="fname" size="30" /></li>
<li><label>Last Name</label><input type="text" name="lname" size="30" /></li>
<li><label>Phone</label><input type="text" name="phone" size="30" /></li>
<li><label>Email</label><input type="text" name="email" size="30" /></li>
<li><input type="submit" name="submit" id="submit" value="Submit" />
</ul>
</div>
</form>
<script type="text/javascript" src="input.js"></script>
<script type="text/javascript">obj.init();</script>
</body>
</html>
Again thank you for reading !
Simply empty out your span before you validate your input fields.