I have the following loop. The goal is to automatically show text boxes when a user chooses certain options in a dropdown list.
For some reason, in the following code, the loop assigns the “sponsor” field to the associated array for “blurb”. I cannot figure out why. How can I make this work?
Thanks so much.
function add_fields_on_change ()
{
var map = {
"sponsor" : Array("New Sponsor", "new_sponsor"),
"blurb" : Array("New Blurb Suggestion", "new_blurb")
};
for (field in map)
{
alert($('.bound[name='+field+']').val()); //alerts as expected
$('.bound[name='+field+']').change(function() {
alert(map[field][0]); //alerts "New Blurb Suggestion" for both "sponsor" and "blurb" fields
if ($(this).val() == map[field][0])
{
$('.hidden[name='+map[field][1]+']').show();
}
});
}
}
The reason is that the event handler you’re creating (which is a closure) has an enduring reference to the
fieldvariable, not a copy of it as of when the function was created. So all of the event handlers that get created will see the same value offield(the last value assigned to it).Because you’re already using jQuery, the easiest solution is probably to use
$.each:That works because the event handlers close over the call to the iterator function you’re passing into
each, and so they each get their ownfieldargument, which never changes.If you wanted to do it without using
$.eachfor whatever reason, you’d do something like this:It’s the same principle, the event handler closes over the call to
createHandlerand uses thefargument, which is unique to each call, and which we’re never assigning a new value to.Note that I declared the
fieldvariable. That declaration was missing from your original code, which means you were falling prey to the Horror of Implicit Globals.More reading: