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;
			}
		}

Recommended Answers

All 3 Replies

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

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

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.