Return false from within a nested control structure


How do I return false (or true) from within a nested control structure.

For example, I’m using jquery and I would like to do some basic validation:

I want to pass to a custom function named checkDefault every element with the class required.

function checkDefault(elem) {
if(elem.val() == elem.attr(‘title’)) return false;

I would like when I return false from the each loop to also return false from the checkDefault function. Is that possible?

Thanks in advance!

Nope, not with using each

A for loop would be the most straightforward way.

Returning false from jQuery’s .each method just stops the loop from continuing.

You will need to set a variable in the checkDefault function, and return that instead.

function checkDefault(elem) {
    var missingTitle = true;
    elem.each(function () {
        if (elem.val() == elem.attr('title')) {
            missingTitle = false;
    return missingTitle;

Hey thanks for that pmw57!

I considered a similar approach but thought in javascript it might be flimsy because of an experience I had trying to set a variable within an ajax call. Let me explain:

Javascript evaluated the variable in question before ajax had a chance to change the same variables value, even though I had the ajax written at the top of the script.

So I didn’t know whether javascript was as sequential as say php which I have a little more experience with… Because it was executing code written after other areas of code that hadn’t finished yet…

Does that make sense?

The caution makes sense. When AJAX is being done, the asynchronous nature of things can cause problems.

Fortunately though, with almost everything else regarding javascript, it is sequential as expected.

Thanks for enlightening me…