The Linux Page

Setting up an array of JavaScript functions in jQuery

Today I worked a bit with jQuery to create an advanced form. Advanced just because it is tabbed and appears in a pop-up, nothing too major really. Maybe later I'll add some tests to validate the data being entered before someone can submit the form...

In any event, I ran in a problem which was to create a set of click callback functions (event handlers) and each of which should make use of a different index. So... I have 4 tabs and each one has a number: 1, 2, 3, and 4.

Say I call each one of these numbers #tab1, #tab2, #tab3, and #tab4. Now I want to create a click function on each one of them and it seems logical to do this:

  for(var i = 1; i <= 4; ++i) {
    $("#tab" + i).click(function() { show_tab(i); return false; });
  }

Note: The return false is there just to avoid propagation.

So... now when I click on the 1 for the first tab, it calls show_tab(i);. Neat. BUT, the value of i is NOT 1, it's 5. I'm not 100% sure why, it looks (obviously) that the variable i is still being taken from the variable defined in the for() loop and thus it is now 5 and not 1, 2, 3, or 4 as expected.

I have not found a way to fix this problem with a for loop. Instead, I switched to a foreach() loop using jQuery and an array as follow:

  $.each([1, 2, 3, 4], function(index, i) {
    $("#tab" + i).click(function() { show_tab(i); return false; });
  });

Notice that the function itself is the same, except that it accepts two parameters: index and i. The index is the offset in the array and i is the value of the item you're working on. Here I use i since it has the exact value I want to use.

Notice that because we call the function with parameters, it properly saves the parameter used at the time the function is created and not the value of some loop variable at the time the call is made.

jQuery and JavaScript for() loops are wonderful, but you really need to have quite a bit of knowledge and understanding of the language to find solutions like these!