Asynchronous
Asynchronous

Reputation: 3977

Getting the length of a textbox value or content using JavaScript

This is something that's driving me nuts:

I have this code and it works: I am trying to learn JavaScript before becoming addicted to JQuery. My sample project involves getting the value of the text-box, and validating according to it's length. the name of the form is membership.

Example: This works:

function validateForm()
{
    var element = document.membership;

    if(element.txtName.value == "")
    {
        element.txtName.className = "alert";
    }
    else
    {
        element.txtName.className = "";
    }
}

But this doesn't:

function validateForm()
{
    var element = document.membership;
    var nameLenght = element.txtName.value.lenght;

    if(nameLenght < 1)
    {
        element.txtName.className = "alert";
    }
    else
    {
        element.txtName.className = "";
    }
}

Just an FYI: I am new to JavaScript but very familiar with the syntax. I just want to learn the basics and move up.

I even read some solutions on here but feel I am simply sinking deeper.

Thanks for your help.

Upvotes: 4

Views: 55470

Answers (2)

Aruna Prabhath
Aruna Prabhath

Reputation: 242

you can use this function as well

var a = txtName.value;
            if (a.length < 1) {
                alert('your message');
                return false;
            }

Upvotes: 0

Ivan Chernykh
Ivan Chernykh

Reputation: 42196

May be it is just because of typo in length here:

element.txtName.value.lenght;

must be element.txtName.value.length;.

If you want it to run every time user presses key , then look here: How to check string length with JavaScript

Upvotes: 12

Related Questions