[Javascript] Targeting the correct form??

David Dorward david at dorward.me.uk
Wed Feb 25 11:07:35 CST 2009


Terry Riegel wrote:
> Hello everyone. I am struggling with a particular function. I have a  
> page with multiple forms on it. I am applying unobtrusive javascript  
> to it and am having difficulty targeting the right form with my code.  
> Via an onload I call forms() and that works great. When I go to submit  
> the form I simply alert the id of the form submitted. At least thats  
> what I would think my code would do (listed below). Instead regardless  
> of what form button I click on It alerts the id of the last form  
> element on the page.
>   
This is a common error.

> Any help will be greatly appreciated.
>
>
> function forms(h) {
>   var daItems = $$('.'+h);
>   for (iItem=0; iItem < daItems.length; iItem++) {
>     var o=daItems[iItem]
>     o.onsubmit=function(){return doforms(o)};
>    }
>   }
>
>   function doforms(o) {
>   alert(o.id);
>   return false;
>   }
>   

When you assign function(){return doforms(o)};, "o" means "The variable 
o" not "The current value of the variable o".

Since the loop keeps going - o ends up being the last value that it 
reaches by the time the function is ever called.

I could explain how to use closures to work around this, but its much 
simpler to just suggest you use this instead.

o.onsubmit=function(){return doforms(this)};


Or even easier:
var doforms = function () {
  alert(this.id);
  return false;
};

and 
o.onsubmit=doforms;


And just for good measure, insert rant about obfuscated code: 
http://dorward.tumblr.com/post/79674407/the-dollar-function-must-die

-- 
David Dorward
http://dorward.me.uk/



More information about the Javascript mailing list