Javascript 如何使用Javascript检查值长度?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12507244/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 10:34:21  来源:igfitidea点击:

How to check value length with using Javascript?

javascript

提问by Teodoris

Hello everyone I would like to ask how to check value's length from textbox ?

大家好,我想问一下如何从文本框中检查值的长度?

Here is my code :

这是我的代码:

@*<script>
    function validateForm() {
        var x = document.forms["frm"]["txtCardNumber"].value;
        if (x == null || x == "" ) {
            alert("First name must be filled out");
            return false;
        }
    }
</script>*@

When I run my script yeap I got alert message but I'm trying to add property which control the texbox' input length.

当我运行我的脚本 yeap 时,我收到了警报消息,但我正在尝试添加控制文本框输入长度的属性。

回答by Darin Dimitrov

You could use x.lengthto get the length of the string:

您可以使用x.length来获取字符串的长度:

if (x.length < 5) {
    alert('please enter at least 5 characters');
    return false;
}

Also I would recommend you using the document.getElementByIdmethod instead of document.forms["frm"]["txtCardNumber"].

此外,我建议您使用该document.getElementById方法而不是document.forms["frm"]["txtCardNumber"].

So if you have an input field:

因此,如果您有一个输入字段:

<input type="text" id="txtCardNumber" name="txtCardNumber" />

you could retrieve its value from the id:

您可以从 id 中检索其值:

var x = document.getElementById['txtCardNumber'].value;

回答by Praveen Kumar Purushothaman

Still more better script would be:

更好的脚本是:

<input type="text" name="txtCardNumber" id="txtCardNumber" />

And in the script:

在脚本中:

if (document.getElementById(txtCardNumber).value.length < 5) {
    alert('please enter at least 5 characters');
    return false;
}