简体   繁体   中英

.length showing value 1 in javascript

I have the following form

<form name="client-login" method="post" onsubmit="return Check_form();">
  <label>Email</label><input type="text" name="client-email" value=""><br/>
  <label>Password</label><input type="password" name="password"  value="">
  <input type="submit" name="submit" value="submit"">
</form>

And below is the javascript function Check_form()

   <script>
function Check_form()
{
    var email    = document.getElementsByName("client-email");
    var password = document.getElementsByName("password");
    alert(email.length);
    if(email.length == null)
    {
        email.style.border='1px solid red';
        return false;
    }
    else if(password.length == null)
    {
        password.style.border='1px solid red';
        return false;
    }
    return false;
}

</script>

But despite me submitting with empty fields it is alerting value as 1 for the client email. Any idea what is wrong.

In the above JS you have taken email variable which contains array of email text field named "client-email".

To check the email lentgh use this:

alert(email[0].value.length);

document.getElementsByName() returns nodeList.

Either use document.getElementById() or

you can use document.getElementsByName("client-email")[0] which will return the first element from that nodelist

document.getElementsByName() returns an array

So in your case use document.getElementById()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM