使用 JavaScript 获取文本框值或内容的长度
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17130936/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Getting the length of a textbox value or content using JavaScript
提问by Asynchronous
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.
我有这个代码并且它有效:我正在尝试在对 JQuery 上瘾之前学习 JavaScript。我的示例项目涉及获取文本框的值,并根据它的长度进行验证。表单的名称是members。
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.
仅供参考:我是 JavaScript 新手,但对语法非常熟悉。我只想学习基础知识并向上移动。
I even read some solutions on here but feel I am simply sinking deeper.
我什至在这里阅读了一些解决方案,但觉得我只是陷入了更深的境地。
Thanks for your help.
谢谢你的帮助。
回答by Cherniv
May be it is just because of typo in length
here:
可能只是因为length
这里的错字:
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
必须是element.txtName.value.length;
。
如果您希望它在每次用户按下 key 时运行,请查看此处:如何使用 JavaScript 检查字符串长度