Reputation: 23216
The following function's if
statement never executes even when i have filled both the text-field and the
password field. The alert
function works fine before the if
statement but the alert
function after the
if statement never works.
Here is the function :
<script type="text/javascript">
function CheckForMissingFields() {
alert("before if statement");
if(document.getElementById("username").length != 0 && document.getElementById("password").length != 0) {
document.getElementByName("SignInButton").disabled = 'false';
alert("inside if statement");
}
alert("outside if statement");
}
Initially the state of the button SignIn
is disabled. I look to enable it when the both the fields are done with.
What could be the reason for if
statement never working ?
Following is the corresponding HTML sign-in snippet :
<ul> <form method="post" action="#">
<li> <input type="text" id="username" value="Username or Email" size="25" name="UserID" onfocus="emptyTextField()" /> </li>
<li> <input type="password" id="password" value="password" size="25" name="UserPassword" onfocus="emptyPasswordField()" />
<center><input type="submit" value="sign-in" style="font-size:20px" name="SignInButton" disabled="true"/> </center>
</li>
</form>
</ul>
Upvotes: 0
Views: 277
Reputation: 176896
how about
function trim(stringToTrim) {
return stringToTrim.replace(/^\s+|\s+$/g,"");
}
just create function as above which trims space in string and than replace your if condition as below will do work for you..
if(trim(document.getElementById("username").value) != "" &&
trim(document.getElementById("password").value) != "")
Upvotes: 1
Reputation: 11908
You are trying to get the length of html tags. I think you want to get the contents of the input fields instead.
Like this:
if(document.getElementById("username").value.length != 0 &&
document.getElementById("password").value.length != 0)
That answers the original question. Then, if you want a space to be considered as nothing, you should use a function that trims away spaces (like jQuery.trim
) before taking the length of the string.
Upvotes: 3
Reputation: 122906
Use: if (document.getElementById("username").value.length)
etc. In other words, you'll need the value
of the field.
No need for !=0
by the way, if the value.length === 0
value.length
will evaluate to false
(falsy
)
Before checking the value length you may want to trim the value, so:
if (document.getElementById("username").value.replace(/^\s+|\s+$/,'').length)
Upvotes: 7
Reputation: 1760
I'm confused: Where are you calling your
CheckForMissingFields()
function from? If you don't call that, you never will see the if statement work. Also, you'll need to re-evaluate each time the textboxes change, so try binding that function to the change event or blur event.
Upvotes: 0
Reputation: 129792
getElementById
yields a DOM node. In your case an input field. It doesn't have a length
property, but its value
does.
Upvotes: 3