1

I have a situation whereby, i need to create buttons dynamically and i need to attached an onclick event to each of them. All of the above is done fine. However, when one of the button is clicked, the function that is called i.e (animate(poly,map)) uses the last known value of poly and map as parameters. I stuck with this problem since this morning. Please help. Thanks

for(var k=0;k<arr_altern.length;k++){
         my_div=create_div_interchange(arr[i],1,78,visited_bus,interchange_arr,arr_altern[k],null, my_interchange_array);

        $('#results').append(my_div);
        var x='animate';
        var v='#animater';
        v+=div_id;
        x+=div_id;
        map=create_map(div_id);
        var poly=retrieve_results_edges(bus_stops_visited,map);

        var strVar="";
        strVar += "<span class=\"animate\">";
        strVar += "<input type=\"button\"  id="+x+" name=\"animate\"  value=\"Animate\" \/>";
        strVar += "<\/span>";


        $(v).append(strVar);



        document.getElementById(x).onclick=function test(){

                animate(poly,map);

     }

     set_map(map);


    set_polyline_color(my_traversed_edge,map);

        }

UPDATE SOLUTION:

i've replaced  

    document.getElementById(x).onclick=function test(){

                animate(poly,map);

     }

BY

$('#'+x).bind('click',{poly:poly,map:map}, function(event) {
             animate(event.data.poly,event.data.map)
      });
5
  • 1
    The problem is that you keep setting the value of the same variable (a global property in the case of map) which is then accessed later. There is only one variable called map and one variable called poly in the code. Please search StackOverflow for "javascript last value loop" which will lead to examples of what is going wrong, and how to correct it. Commented Feb 24, 2012 at 23:50
  • yes, of course, you're changing the values of poly and map throughout the loop and the last values stay in. You need to store those of each of the buttons separately Commented Feb 24, 2012 at 23:52
  • 1
    stackoverflow.com/questions/6425062/… , stackoverflow.com/questions/2520587/… , stackoverflow.com/questions/6599157/… , etc. Pick one. Commented Feb 24, 2012 at 23:52
  • 2
    Okay, found a really good "simple" case of this: stackoverflow.com/questions/5555464/javascript-closure-of-loop Commented Feb 24, 2012 at 23:57
  • 1
    You have a syntax error $(#results).append(my_div);, missing " Commented Feb 25, 2012 at 0:03

3 Answers 3

3

You are declaring the map variable without the var keyword so it's being created in the global scope, so there is only one map variable that gets it's value over-written each loop.

for(var k=0;k<arr_altern.length;k++){
    (function (k) {
        my_div=create_div_interchange(arr[i],1,78,visited_bus,interchange_arr,arr_altern[k],null, my_interchange_array);

        $('#results').append(my_div);
        var x      = 'animate' + div_id,
            v      = '#animater' + div_id,
            map    = create_map(div_id),
            poly   = retrieve_results_edges(bus_stops_visited, map),
            strVar = '<span class="animate"><input type="button"  id="' + x + '" name="animate"  value="Animate" /><\/span>';

        $(v).append(strVar);

        document.getElementById(x).onclick=function test(){

            animate(poly,map);

        }

        set_map(map);


        set_polyline_color(my_traversed_edge,map);
    })(k);
}

Running your code inside of an IIFE (Immediately-Invoked Function Expression) will create a new scope for the code within it. This allows you to declare variables at the time of running and they will hold their value into the future (for instance they will be available to event handlers that fire in the future). Notice I used the var keyword when declaring all the variables so they are created in the current scope.

Update

You could also use $.each() to scope your code:

$.each(arr_altern, function (k, val) {
        my_div=create_div_interchange(arr[i],1,78,visited_bus,interchange_arr,arr_altern[k],null, my_interchange_array);

        $('#results').append(my_div);
        var x      = 'animate' + div_id,
            v      = '#animater' + div_id,
            map    = create_map(div_id),
            poly   = retrieve_results_edges(bus_stops_visited, map),
            strVar = '<span class="animate"><input type="button"  id="' + x + '" name="animate"  value="Animate" /><\/span>';

        $(v).append(strVar);

        document.getElementById(x).onclick=function test(){

            animate(poly,map);

        }

        set_map(map);


        set_polyline_color(my_traversed_edge,map);
});
Sign up to request clarification or add additional context in comments.

Comments

0

Try to use self-invocation

(function (x, poly, map) {

     document.getElementById(x).onclick=function test(){

                animate(poly,map);

     }


})(x, poly, map);

6 Comments

Yes, but why? How does it change things?
@pst By passing the vars as parameters to a function, and calling it immediately, you bind (copy) the current values of the variables to that function's scope. JavaScript only has function scope, not block scope.
@paislee You don't pass variables ;-) [nit, nit, just trying to flush out this answer some]
I got the solution. I've used the JQuery bind method. Thanks for all suggestions!
@pst I like precisions. What, pray tell, does one pass?
|
0

You can use jQuery proxy

var buttons = $("a");
for (var i = 0; i < buttons.length; i++){
  $(buttons[i]).unbind("click").click(
    $.proxy(
      function(){
        alert(this);
        return false;
      },
      i
    )
  );
}

or capture your arguments by creating new function

var buttons = $("a");
for (var i = 0; i < buttons.length; i++){
  $(buttons[i]).unbind("click").click(
    function(arg){
      return function(){
        alert(arg);
        return false;
      };
    }(i)
  );
}

Just run one of this examples in firebug console to see the effect.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.