1

Given the following jQuery expression

    $("form").each(function () {
        var info = validationInfo(this);
        if (info) {
            info.attachValidation();
        }
    });

The selector chooses all forms on the page, and then for each 'form' found, it attaches a function.

My question is when does the JS in this function actually run? Does the JS in the function execute when it is attached?

Kasaku
  • 2,192
  • 16
  • 26
John Livermore
  • 30,235
  • 44
  • 126
  • 216
  • 1
    I think you need to enlighten us about what `validationInfo()` and `attachValidation()` are before we can answer that question. – Brad Christie Dec 22 '10 at 20:19
  • 1
    The JS in the function runs when it's called. – gen_Eric Dec 22 '10 at 20:20
  • I appreciate all the answers thus far. It seems I have submitted a bad example. I would like to update that with a better one (I think it is anyway), but it would invalidate the posts that have already been given. Should I start a different thread? Or should I edit the code in the original question? Not sure of the protocol – John Livermore Dec 22 '10 at 21:29
  • Just to clarify: the `.each()` method does not "attach" the function to each form. It just execute the function. When binding events the term "attaches a function" is correct, that's not the case here. The `.each()` just iterates through a collection - nothing more, nothing less. – Shadow The GPT Wizard Oct 11 '11 at 11:03

2 Answers2

2

When is attachValidation() ran? It's executed as soon as it's called in the loop.

simshaun
  • 21,263
  • 1
  • 57
  • 73
2

It all depends where that code is located.

It will run if you include that code block in a $(function(){...} block which runs when the document is parsed:

$(function(){
    $("form").each(function () {
        var info = validationInfo(this);
        if (info) {
            info.attachValidation();
        }
    });
})

Though based on your use case, you may want to validate all forms when a user event happens like clicking a button. In that case you'd have to include the code in a function which you execute when the user clicks a button:

//Bind function to button
$("#mybutton").live('click', doValidation);

//Do validation
function doValidation() {
    $("form").each(function () {
        var info = validationInfo(this);
        if (info) {
            info.attachValidation();
        }
    });
}
Community
  • 1
  • 1
Marcus Leon
  • 55,199
  • 118
  • 297
  • 429
  • "That code alone will never run per se."...sure it will, if it's located after any `
    ` elements...your first line is an incorrect statement.
    – Nick Craver Dec 22 '10 at 20:28
  • Fair enough. Point being it all depends where the code is placed.. updated the post.. – Marcus Leon Dec 22 '10 at 20:31