简体   繁体   English

使用 JavaScript 获取文本框值或内容的长度

[英]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.我有这段代码并且它有效:在沉迷于 JQuery 之前,我正在尝试学习 JavaScript。我的示例项目涉及获取文本框的值,并根据它的长度进行验证。 the name of the form is membership .表格的名称是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.仅供参考:我是 JavaScript 的新手,但对语法非常熟悉。 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.谢谢你的帮助。

May be it is just because of typo in length here: 可能这只是因为错字的length在这里:

element.txtName.value.lenght;

must be element.txtName.value.length; 必须为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 如果您希望它在用户每次按键时运行,那么请看这里: 如何使用JavaScript检查字符串长度

you can use this function as well你也可以使用这个 function

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM