Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When does an input field value equals '', null or undefined

In which cases do an input field value equals '', null or undefined.

I'm trying to check empty fields

if($('#cur').val() == 'undefined' || $('#cur').val() == '' || $('#cur').val() == 'null'){
    alert('Blank');
}
like image 867
ptamzz Avatar asked May 23 '26 23:05

ptamzz


1 Answers

The value of an input element will always be a string. You can safely just compare to the empty string:

if($("#cur").val() === "") {
    alert("Blank");
}

You are currently checking for the string literals "undefined" and "null". That would only be the case if the value of the input was actually the string "undefined" or "null". For example:

<!--This would be blank according to your original test-->
<input type="text" value="undefined">

It may be worth noting that if the input contains blank spaces but nothing else, and you want to count that as empty, the above will not suffice. You can use the jQuery trim function to remove leading/trailing white space from a string:

if($.trim($("#cur").val()) === "") {
    alert("Blank");
}
like image 120
James Allardice Avatar answered May 26 '26 12:05

James Allardice



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!