The reason is that the event handler you're creating (which is a closure) has an enduring reference to the field variable, 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 of field (the last value assigned to it).
Because you're already using jQuery, the easiest solution is probably to use $.each:
function add_fields_on_change ()
{
var map = {
"sponsor" : Array("New Sponsor", "new_sponsor"),
"blurb" : Array("New Blurb Suggestion", "new_blurb")
};
$.each(map, function(field, value) {
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][2]+']').show();
}
});
});
}
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 own field argument, which never changes.
If you wanted to do it without using $.each for whatever reason, you'd do something like this:
function add_fields_on_change ()
{
var map = {
"sponsor" : Array("New Sponsor", "new_sponsor"),
"blurb" : Array("New Blurb Suggestion", "new_blurb")
};
var field;
for (field in map)
{
alert($('.bound[name='+field+']').val()); //alerts as expected
$('.bound[name='+field+']').change(createHandler(field));
}
function createHandler(f) {
return function() {
alert(map[f][0]); //alerts "New Blurb Suggestion" for both "sponsor" and "blurb" fields
if ($(this).val() == map[f][0])
{
$('.hidden[name='+map[f][3]+']').show();
}
};
}
}
It's the same principle, the event handler closes over the call to createHandler and uses the f argument, which is unique to each call, and which we're never assigning a new value to.
Note that I declared the field variable. That declaration was missing from your original code, which means you were falling prey to the Horror of Implicit Globals.
More reading:
["New Sponsor", "new_sponsor"]for creating an array. UsingArraycan lead to surprising quirks - see whatArray(2)returns.