Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: checking if the value of a field is null (empty)

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?

like image 348
ziiweb Avatar asked Nov 22 '10 10:11

ziiweb


People also ask

How do I check if a variable is empty or null in jQuery?

If myvar contains any value, even null, empty string, or 0, it is not "empty". To check if a variable or property exists, eg it's been declared, though it may be not have been defined, you can use the in operator. Show activity on this post.


1 Answers

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 ) {...} } 
like image 76
Guffa Avatar answered Oct 10 '22 15:10

Guffa