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.

Asynchronous
  • 3,917
  • 19
  • 62
  • 96
  • 1
    Did you really mean lenght or length? – PSL Jun 16 '13 at 06:58
  • Are you able to retrieve your element by using document.membership;? I would suggest using document.getElementById() or getElementsByClassName () – MartinElvar Jun 16 '13 at 06:59
  • Sorry about the type: I meant: length. My bad. It's called being too used to intellisense. I am using NotePad. – Asynchronous Jun 16 '13 at 07: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? – Asynchronous Jun 16 '13 at 07:08
  • So the problem really was the typo? Then you should revert the edit. – Felix Kling Jun 16 '13 at 07:10
  • @Filix Kling: I did, thanks again! – Asynchronous Jun 16 '13 at 07:12

2 Answers2

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

Community
  • 1
  • 1
Ivan Chernykh
  • 41,617
  • 13
  • 134
  • 146
0

you can use this function as well

var a = txtName.value;
            if (a.length < 1) {
                alert('your message');
                return false;
            }
Aruna Prabhath
  • 206
  • 2
  • 10