Can someone tell me what I am doing wrong on this? I have seen people use quotes inside the GetElementsByName(), and I have seen people who didn't. The resulting script does nothing when the username is blank.
if (document.getElementsByName('username').length < 1) {
alert("Username must be filled out");
return false;
}
The call from HTML is this:
<form name="stafflogin" action="usermain.php" onsubmit="return validateForm()" method="post">
<p>Username:
<input type="text" id="username" name="username" size="15" value=""/> <br />
Password: <input type="password" id="userpass" name="password" size="15" value=""/>
<input type="submit" id="submit" name="submit" value=" - Submit - ">
</p>
I know it must be something simple, so forgive me in advance for such foolishness.
In this case it propably would be smarter to use document.getElementById("username")
instead - this returns a single element and not an array.
Cheers,
Florian
document.getElementsByName('username').length < 1
says "if there are no elements in the document named 'username'" -- which will always be false, as there is such an element in the document, and the return value of getElementsByName
is an array.
What you meant to do instead is
if (document.getElementsByName('username')[0].value.length < 1)
but I really think it's better (easier to read and harder to mess up) to use
if (document.getElementsByName('username')[0].value == "")
Since the target element also has an id, it's even better to use getElementById
which directly returns the element you are looking for (no array to confuse things) and does so faster:
if (document.getElementById('username').value == "")