jQuery: checking if the value of a field is null (empty)
that depends on what kind of information are you passing to the conditional..
sometimes your result will be null
or undefined
or ''
or 0
, for my simple validation i use this if.
( $('#id').val() == '0' || $('#id').val() == '' || $('#id').val() == 'undefined' || $('#id').val() == null )
NOTE: null
!= 'null'
The value of a field can not be null, it's always a string value.
The code will check if the string value is the string "NULL". You want to check if it's an empty string instead:
if ($('#person_data[document_type]').val() != ''){}
or:
if ($('#person_data[document_type]').val().length != 0){}
If you want to check if the element exist at all, you should do that before calling val
:
var $d = $('#person_data[document_type]');
if ($d.length != 0) {
if ($d.val().length != 0 ) {...}
}
Assuming
var val = $('#person_data[document_type]').value();
you have these cases:
val === 'NULL'; // actual value is a string with content "NULL"
val === ''; // actual value is an empty string
val === null; // actual value is null (absence of any value)
So, use what you need.
I would also trim the input field, cause a space could make it look like filled
if ($.trim($('#person_data[document_type]').val()) != '')
{
}