Is this a good way to check if the value of a field is null
?
if($('#person_data[document_type]').value() != 'NULL'){}
Or is there a better way?
This question is related to
javascript
jquery
forms
jquery provides val()
function and not value()
. You can check empty string using jquery
if($('#person_data[document_type]').val() != ''){}
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'
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.
My Working solution is
var town_code = $('#town_code').val();
if(town_code.trim().length == 0){
var town_code = 0;
}
I would also trim the input field, cause a space could make it look like filled
if ($.trim($('#person_data[document_type]').val()) != '')
{
}
_helpers: {
//Check is string null or empty
isStringNullOrEmpty: function (val) {
switch (val) {
case "":
case 0:
case "0":
case null:
case false:
case undefined:
case typeof this === 'undefined':
return true;
default: return false;
}
},
//Check is string null or whitespace
isStringNullOrWhiteSpace: function (val) {
return this.isStringNullOrEmpty(val) || val.replace(/\s/g, "") === '';
},
//If string is null or empty then return Null or else original value
nullIfStringNullOrEmpty: function (val) {
if (this.isStringNullOrEmpty(val)) {
return null;
}
return val;
}
},
Utilize this helpers to achieve that.
Try
if( this["person_data[document_type]"].value != '') { _x000D_
console.log('not empty');_x000D_
}
_x000D_
<input id="person_data[document_type]" value="test" />
_x000D_
Source: Stackoverflow.com