2

How is it that the first event bind works for all the submit buttons, yet the second applys the css only for the last one, regardless of what form it is listening to?

for (var i=0; i < len; i++) {
    var divI = "ind-" + i;
    var formID = document.forms["form-" + i];

    $(formID).bind("submit", validate);
    $(formID).bind("change", function(){
        $('#' + divI).css("background-color","green");
    });
}
2
  • @Marcus Was it really necessary to edit this? You've revived a question from 8 years ago. Commented Jan 15, 2019 at 21:34
  • Necessary? No. Value added? Yes. I had a slightly hard time reading the code so I just cleaned up the whitespace a bit. Have I caused you grief somehow? Commented Jan 16, 2019 at 22:02

1 Answer 1

1

It closure. Check this one jquery and javascript's closure

Sign up to request clarification or add additional context in comments.

4 Comments

Thanx @George Kastrinis, but what exactly is closure?
Closure is a combination of a function and some elements from its environment. Closure on wikipedia In your case, you have a function for 'change' but it uses divI which is not defined inside the function. It is defined in the function's environment.
OK thanx, I see from your link how to fix it, but why does it fail initially?
Check the last comment on the above link. "No, the closure gives access to the parent's variable i, which by the time the click() event is called, has beens set to 5"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.