0

I have a function I want to attach to all forms passing the form itself as an argument. When I submit the form, I see that the function gets called, but the argument is either null or some other element in the DOM.

This method is already called within a class, so this is probably the wrong thing to pass, but forms[i] did not work either. What do I pass in place of the ?, or is there a better way?

var forms=this.content.getElementsByTagName('form');
for(var i=0;i<forms.length;++i){
    // TODO: handle if there is already an onsubmit() function
    forms[i].onsubmit=function(){SubmitForm(?);}
}
steveo225
  • 11,394
  • 16
  • 62
  • 114
  • Check this question: http://stackoverflow.com/questions/1451009/javascript-infamous-loop-issue – Ram Aug 13 '14 at 12:24
  • @undefined, in this particular case since onsubmit callback is usually has its context set to the form couldn't OP just do `SubmitForm(this);`, instead of dealing with closures – Patrick Evans Aug 13 '14 at 12:28
  • @PatrickEvans—"context"? You mean the listener's *this* will be set to the element. Functions have an execution context, of which *this* is but one parameter. – RobG Aug 13 '14 at 12:32
  • @RobG, yes that is what I mean the execution context. I was just addressing the issue of passing the form element, as that is all OP mentions, they do not mention any other arguments needing passed besides in the title. – Patrick Evans Aug 13 '14 at 12:36

1 Answers1

1

You can use this, since it's inside a loop, it refers to the current form.

forms[i].addEventListener("submit", function() {
    SubmitForm(this);
});
BenMorel
  • 34,448
  • 50
  • 182
  • 322
Nick Rameau
  • 1,258
  • 14
  • 23