Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

jquery

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)?

like image 982
user532104 Avatar asked Jan 18 '11 10:01

user532104


People also ask

How check object is null or not in jQuery?

So always use . length or $. isEmptyObject() function to find out whether object is empty, null or has some elements.

What is $( This val () in jQuery?

The val() method is an inbuilt method in jQuery which is used to returns or set the value of attribute for the selected elements. This method apply on the HTML form elements. Syntax: There are three ways to use this method which are given below: $(selector).val()

How do I check if a variable is empty or null in jQuery?

If myvar contains any value, even null, empty string, or 0, it is not "empty". To check if a variable or property exists, eg it's been declared, though it may be not have been defined, you can use the in operator. Show activity on this post.

What is Val in JS?

Definition and Usage. The val() method returns or sets the value attribute of the selected elements. When used to return value: This method returns the value of the value attribute of the FIRST matched element.


4 Answers

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

like image 51
David Hedlund Avatar answered Nov 04 '22 21:11

David Hedlund


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

like image 36
Steve Jalim Avatar answered Nov 04 '22 20:11

Steve Jalim


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');
     }
}

like image 30
WraithNath Avatar answered Nov 04 '22 22:11

WraithNath


make your check like this

if (sizeVariable.val() === undefined || sizeVariable.val().length == 0)
like image 39
BvdVen Avatar answered Nov 04 '22 22:11

BvdVen