Asynchronous Asynchronous - 3 months ago 32
Javascript Question

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.

Answer

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

Comments