Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

JQuery containsBlank function

Hello treepeople, Can some one demystify the containsBlacnk Function found on the java script tutorial :http://teamtreehouse.com/library/websites/build-an-interactive-website/form-validation-and-manipulation/checking-values.

Our goal is to see whether the required values are empty or not I can boil down my understanding to : the code checks If(val()==""), and push the results (true or false) into the array. I dont get how the if statement checks inside the each method for true or false and pushes the result into an array.

Regards S

1 Answer

Andrew Chalkley
STAFF
Andrew Chalkley
Treehouse Guest Teacher

The each() method cycles over all required fields i.e. with the class of .required.

$required.each(function(){

});

The $(this).val() retrieves the value for the current required field it's looping over. By using a conditional operator like == it will make the line now return a boolean value. So $(this).val() == "" will equal either true or false. That's how conditional statements work in an if condition.

So instead of doing this...

$required.each(function(){
    if($(this).val() == "") {
      blanks.push(true);
    } else {
      blanks.push(false);          
    }
});

... we can do it less verbose like this, since the condition we're testing for is going to be stored in an array.

$required.each(function(){
    blanks.push($(this).val() == "");
});

Does that make any more sense?

Regards, Andrew