user532104
user532104

Reputation: 1423

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

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

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:

  1. the variable exists
  2. 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)?

Upvotes: 7

Views: 77035

Answers (6)

Yousif Al-Raheem
Yousif Al-Raheem

Reputation: 511

In jQuery you can use:

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

or if for some reason it didn't work you can use:

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

Upvotes: 0

David Hedlund
David Hedlund

Reputation: 129802

You can test if the input field exists as such:

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

If it doesn't, val() will return undefined.

You could skip immediately to the following:

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

... since both undefined and "" would resolve to false

Upvotes: 20

baked
baked

Reputation: 245

Have you tried...?

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

Upvotes: 0

BvdVen
BvdVen

Reputation: 2961

make your check like this

if (sizeVariable.val() === undefined || sizeVariable.val().length == 0)

Upvotes: 1

Steve Jalim
Steve Jalim

Reputation: 12195

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

Upvotes: 5

WraithNath
WraithNath

Reputation: 18013

is sizeVarialbe null when trying to check the length?



function size(sender, args) {

    var sizeVariable = $("input[id$='txtHello']");

    if (sizeVariable != null)
    {
      if (sizeVariable.val().length == 0)
      {
          args.IsValid = false;
      }
     }
     else
     {
       alert('error');
     }
}

Upvotes: 1

Related Questions