By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
459,238 Members | 1,661 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 459,238 IT Pros & Developers. It's quick & easy.

using closure to pinpoint a form to empty itself

P: 7

I'm trying to use closure to pinpoint a form from a list of forms with the same name to erase its onblur function when the chosen form goes onblur.
For example, there will be indefinite numbers of text input forms with the same name "name[]" like this and same function "calculate()" when onblur,

name[] onblur= function () {calculate()};
name[] onblur= function () {calculate()};
name[] onblur= function () {calculate()};

And, when someone chooses any of the fields and goes onblur, it will intially execute a function, but right after that, onblur function will be deleted to prevent the same function being executed from the same form. So if I chose the second input field, the result would be,

name[] onblur= function () {calculate()};
name[] onblur= "";
name[] onblur= function () {calculate()};

So, I wrote this function employing the closure concept. However, for some reason, it nullifies the onblur function one by one from the top instead of just nullifying the chosen field.

What am I doing wrong?

Expand|Select|Wrap|Line Numbers
  1. var nameInputs = document.getElementsByName("name[]");
  2. for (var j=0; j<nameInputs.length; j++) {
  3.     var nameInput = nameInputs[j];
  4.     nameInput.onblur = function(value) {return function() {
  5.     nameInput.onblur = "";
  6.     }
  7.     }(j);
  8. };
Dec 23 '08 #1
Share this Question
Share on Google+
1 Reply

Expert Mod 5K+
P: 8,639
in this case I recommend the use of removeEventListener() (works if you attached the event via addEventListener()) and I think that you have to define the event removal in the calculate() function.

something like*
Expand|Select|Wrap|Line Numbers
  1. function calculate()
  2. {
  3. // code comes here
  4. this.removeEventListener("blur", calculate, false);
  5. }
  6. // for each Input ...
  7. Input.addEventListener("blur", calculate, false);

* some expert correct me if I'm wrong here
Dec 23 '08 #2

Post your reply

Sign in to post your reply or Sign up for a free account.