JQuery: checking if a field value is null (empty)

Is this a good way to check if a field value is null?

if($('#person_data[document_type]').value() != 'NULL'){} 

Or is there a better way?

+71
javascript jquery forms
Nov 22 '10 at 10:43
source share
6 answers

The value of the field cannot be null; it is always a string value.

The code checks to see if the string value is a "NULL" string. You want to check if this is an empty string:

 if ($('#person_data[document_type]').val() != ''){} 

or

 if ($('#person_data[document_type]').val().length != 0){} 

If you want to check if an element exists at all, you must do this before calling val :

 var $d = $('#person_data[document_type]'); if ($d.length != 0) { if ($d.val().length != 0 ) {...} } 
+118
Nov 22 '10 at 10:47
source share
โ€” -

I would also crop the input field, because the space might look like filled

 if ($.trim($('#person_data[document_type]').val()) != '') { } 
+35
Nov 22 2018-10-22
source share

Assuming

 var val = $('#person_data[document_type]').value(); 

you have such 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.

+11
Nov 22 '10 at 10:50
source share

which depends on what information you pass to the conditional ..

sometimes your result will be null or undefined or '' or 0 , for my simple check I use this if.

 ( $('#id').val() == '0' || $('#id').val() == '' || $('#id').val() == 'undefined' || $('#id').val() == null ) 

NOTE : null ! = 'null'

+8
May 20 '15 at 19:52
source share
 _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; } }, 

Use these helpers to achieve this.

+3
Jan 28 '16 at 8:07
source share

jquery provides the function val() and not value() . You can check empty string using jquery

 if($('#person_data[document_type]').val() != ''){} 
0
Nov 22 '10 at 10:48
source share



All Articles