Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the length of a textbox value or content using JavaScript

Tags:

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.

like image 460
Asynchronous Avatar asked Dec 15 '22 09:12

Asynchronous


1 Answers

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

like image 78
Ivan Chernykh Avatar answered Apr 06 '23 00:04

Ivan Chernykh