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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 17:49:05  来源:igfitidea点击:

Javascript/JQuery - val().length' is null or not an object

jquery

提问by user532104

I have the error val().lengthis 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”语句上。我想检查是否:

  1. the variable exists
  2. if there is something in the variable
  1. 变量存在
  2. 如果变量中有东西

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 undefinedand ""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 )