0

I am trying to create an anonymous function for onchange event of file field, so that when a file is selected, the covering text field gets that value. I know how to accomplish this by adding onchange="", but I'd prefer not do that. The code that I have almost works, except that the function in the for loop can't call on the "i" variable that the loop uses.

for( i = 0; i < source.length; i++) {
		source[i].onchange = function() {
			name[i].value = this.value;
			}
		}
2
Contributors
3
Replies
4
Views
7 Years
Discussion Span
Last Post by Airshow
0

Aha, that won't work because name[i] = this.value; will use the vlue of i at the time of execution of the anonymouis function, not the value at the time the function is created.

There's a number of ways round this.

If you have time, read this, in particular the examples which will give some strong clues as to how this type of issue can be resolved elegantly (but not for the Javascript novice).

For a cruder but equally effective solution, try this:

for( i = 0; i < source.length; i++) {
  source[i].associatedObj = name[i];
  source[i].onchange = function() {
  this.associatedObj.value = this.value;
  }
}

I think that will work cross-browser, but you need to test in at least IE and FF. IIRC, IE is more tollerant than Moz in this regard.

If it fails (in FF), then try

source[i].setAttribute('associatedObj', name[i]);

and

source[i].getAttribute('associatedObj').value = this.value;

Airshow

Edited by Airshow: n/a

0

Does the attribute have to be named "associatedObj", or can i add other attributes, like one that has a boolean value?

0

Does the attribute have to be named "associatedObj", or can i add other attributes, like one that has a boolean value?

"associatedObj" is not a keyword, it's just a name of my invention.

You can indeed add other attributes and thay can take any javascript data type (String, Number, Object (including Array), Boolean, Null, undefined).

Airshow

Edited by Airshow: n/a

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.