Javascript/JQuery - val().length' 为 null 或不是对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4723025/
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
Javascript/JQuery - val().length' is null or not an object
提问by user532104
I have the error val().length
is null or not an object" from code:
我有错误val().length
为空或不是对象”来自代码:
function size(sender, args) {
var sizeVariable = $("input[id$='txtHello']");
if (sizeVariable.val().length == 0)
{
args.IsValid = false;
}
}
The error occurs on the "If" statement. I am trying to check if:
错误发生在“If”语句上。我想检查是否:
- the variable exists
- if there is something in the variable
- 变量存在
- 如果变量中有东西
I think the problem lies with point (1). How do I check if the text field exists (to hopefully resolve the issue)?
我认为问题在于点(1)。如何检查文本字段是否存在(希望能解决问题)?
回答by dxh
You can test if the input field exists as such:
您可以测试输入字段是否存在:
if($("input[id$='txtHello']").length > 0) { ... }
If it doesn't, val()
will return undefined
.
如果没有,val()
将返回undefined
。
You could skip immediately to the following:
您可以立即跳到以下内容:
if(!!$("input[id$='txtHello']").val())
... since both undefined
and ""
would resolve to false
......因为这两个undefined
和""
将解析false
回答by Steve Jalim
Try if (sizeVariable.val() == undefined || sizeVariable.val().length == 0)
instead. That way, it'll check whether there's a value first, before trying to see how long it is, if it is present
试试吧if (sizeVariable.val() == undefined || sizeVariable.val().length == 0)
。这样,它会先检查是否有一个值,然后再尝试查看它有多长,如果它存在
回答by BvdVen
make your check like this
像这样做你的支票
if (sizeVariable.val() === undefined || sizeVariable.val().length == 0)
回答by WraithNath
is sizeVarialbe null when trying to check the length?
尝试检查长度时 sizeVarialbe 是否为空?
function size(sender, args) {
var sizeVariable = $("input[id$='txtHello']");
if (sizeVariable != null)
{
if (sizeVariable.val().length == 0)
{
args.IsValid = false;
}
}
else
{
alert('error');
}
}
回答by baked
Have you tried...?
你有没有尝试过...?
if( sizeVariable.size() == 0 )
{
args.IsValid = false;
}
回答by Yousif Al-Raheem
In jQuery you can use:
在 jQuery 中,您可以使用:
if( input.val().length > limit)
or if for some reason it didn't work you can use:
或者如果由于某种原因它不起作用,您可以使用:
if( ( input.val() ).length > limit )