I’m trying to use jQuery and AJAX to validate that users entered a number in a particular field and that they didn’t leave it blank and I’m a little confused as to why I can seem to do one, but not the other.
I’m doing this in a jQuery change()
function so any time they change the value in that field, it updates it in the database without refreshing the whole page and it works fine until I try to use isNull()
to validate.
I’m saving their input to a variable called UserInput
and first checking to make sure it’s a number with this:
if (!isNaN(UserInput))
which works perfectly. I’m also trying to check and make sure it isn’t empty by using this:
if (isNull(UserInput))
Intellisense completes isNull()
for me just like it did for isNaN()
and all appears well in Visual Studio, it compiles without error. I’ve also tried isNullOrUndefined()
here with a similar result, intellisense completes it for me and all seems well. Right up until I change the value in the field, at which point it promptly gives me this error:
JavaScript runtime error: ‘isNull’ is undefined.
I’m not sure why it’s undefined (especially since intellisense is completing it for me) or how to go about defining it.
I also tried this because it seemed like it covered all the bases, not just isNull()
:
https://stackoverflow.com/a/5515349/8767826
and I put an alert()
inside the if
and I didn’t get an error, but my alert didn’t fire either.
The end goal is to get it to change to a zero on the client side if they leave do leave it blank.
Anyway I’m kind of stumped and I appreciate any help anyone can offer.
Thanks
Advertisement
Answer
There’s no need for an isNull
function; you can check
if (UserInput === null)
isNaN
exists because NaN
, unlike every other value in JavaScript, is not equal to itself.
But null
doesn’t mean the field is blank! If the field is blank, its value will be the empty string. Check for that instead:
if (UserInput === '')