4

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.

6
  • 1
    Did you really mean lenght or length? Commented Jun 16, 2013 at 6:58
  • Are you able to retrieve your element by using document.membership;? I would suggest using document.getElementById() or getElementsByClassName () Commented Jun 16, 2013 at 6:59
  • Sorry about the type: I meant: length. My bad. It's called being too used to intellisense. I am using NotePad. Commented Jun 16, 2013 at 7:00
  • Thanks my friends. I am so use to writing C# in visual studio and strong type languages. I have to be very careful because I misspelled but never got an error. even when I pasted the code in Dreamweaver CS6. By the way: The reason I am using var element = document.membership; is because I do not want to call each element by ID individually, is this a bad thing? Commented Jun 16, 2013 at 7:08
  • So the problem really was the typo? Then you should revert the edit. Commented Jun 16, 2013 at 7:10

2 Answers 2

12

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

Sign up to request clarification or add additional context in comments.

Comments

0

you can use this function as well

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.