Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.length showing value 1 in javascript

Tags:

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.

like image 791
Amit Avatar asked Jan 24 '26 02:01

Amit


2 Answers

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);
like image 88
Code Lღver Avatar answered Jan 25 '26 15:01

Code Lღver


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

like image 34
Voonic Avatar answered Jan 25 '26 14:01

Voonic



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!