Javascript scoping != Perl's

I'm doing a lot of jQuery of one of my current clients. Along the way I'm learning fun Javascript gotchas. Here's a demonstration of one scoping difference. Below the .change() event tied to bar works as I expected, but baz is a global variable.

function addARow() {
   var i = $('#next_id').val();
   var d = $("div"),                                      //COMMA then foo
   foo = $("<input>",{id:"foo" + i,size:"3"}).appendTo(d)
   .change(function() { bar.val($(this).val() * 2); })
   .change(function() { baz.val($(this).val() * 2); }),   //COMMA then bar
   bar = $("<input>",{id:"bar" + i,size:"3"}).appendTo(d);//SEMICOLON then baz
   baz = $("<input>",{id:"baz" + i,size:"3"}).appendTo(d);
   $("<br>").appendTo(d);
   $('#next_id').val(i - 1 + 2);   // + 1 would concat 1 onto the string  :)
};

See it in action here. jQuery creates a set of 3 input fields (foo, bar, baz) on each click of "add". When foo is changed by the user, bar and baz are updated. But the wrong baz gets the update.

Live and learn. :)

Leave a comment

About Jay @ Mutation Grid

user-pic Perl / web / database development since 1995. Contact us for your next project.