Javascript / jQuery - val (). Length 'is null or not an object

I have a val().length error val().length is null or not an object "from the code:

 function size(sender, args) { var sizeVariable = $("input[id$='txtHello']"); if (sizeVariable.val().length == 0) { args.IsValid = false; } } 

The error occurs in the "If" statement. I am trying to check if:

  • there is a variable
  • if something is in a variable

I think the problem is at point (1). How to check if a text field exists (so I hope to solve the problem)?

+7
source share
6 answers

You can check if an input field exists as such:

 if($("input[id$='txtHello']").length > 0) { ... } 

If not, val() will return undefined .

You can immediately go to the following:

 if(!!$("input[id$='txtHello']").val()) 

... since both undefined and "" will be allowed to false

+16
source

Try if (sizeVariable.val() == undefined || sizeVariable.val().length == 0) . Thus, it will check if there is a value first before trying to see how long it has been, if it is present

+5
source

is sizeVarialbe null when trying to check length?

 function size(sender, args) { var sizeVariable = $("input[id$='txtHello']"); if (sizeVariable != null) { if (sizeVariable.val().length == 0) { args.IsValid = false; } } else { alert('error'); } } 
+1
source

do your check this way

 if (sizeVariable.val() === undefined || sizeVariable.val().length == 0) 
+1
source

You tried...?

 if( sizeVariable.size() == 0 ) { args.IsValid = false; } 
0
source

In jQuery you can use:

 if( input.val().length > limit) 

or if for some reason this did not work, you can use:

 if( ( input.val() ).length > limit ) 
0
source

All Articles