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:
I think the problem lies with point (1). How do I check if the text field exists (to hopefully resolve the issue)?
So always use . length or $. isEmptyObject() function to find out whether object is empty, null or has some elements.
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()
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.
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.
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
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
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');
}
}
make your check like this
if (sizeVariable.val() === undefined || sizeVariable.val().length == 0)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With