I'm trying to loop through a small form and check for blank fields. I thought it would be simple, but I'm not able to get anything to work. This is my Javascript so far:
var obj = {
fname : document.getElementsByName('fname'),
lname : document.getElementsByName('lname'),
phone : document.getElementsByName('phone'),
email : document.getElementsByName('email'),
span : document.createElement('span'),
txt : document.createTextNode('*Required Field'),
init : function(){
document.getElementsByName('submit').onclick = obj.validate;
},
validate : function(){
var check = document.getElementsByTagName('input');
var len = check.length;
for(var i=0;i<len;i++)
{
if (check[i].value ==='')
{
alert('required');
return false;
};
};
},
};
This is the HTML:
<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" value="Submit" /></li>
</ul>
</div>
</form>
<script type="text/javascript" src="js/main.js"></script>
<script type="text/javascript">obj.init();</script>
</body>
</html>
I thought i should be able to loop through the inputs and alert if the value was blank, but, it's not working for me. Any help would be awesome.