1

I am trying to create buttons dynamically and assining an alert function for each one on a click event.Here is the javascript function as:

function GetTabs(tabObj) {
   for (var t = 0; t < tabObj.views.view.length; t++) {               
        var podObjlen = '';
        var element = document.createElement('input');
        element.id = "btn" + t;
        element.setAttribute("type", "button");
        element.setAttribute("value", "Click");
        element.setAttribute("name", "button");
        podObjlen = tabObj.views.view[t].pod.length;
        document.body.appendChild(element);
        document.getElementById('btn' + t).onclick = (this, "onclick", function {
           alert(podObjlen);                    
        });                
    }
}

No matter what button i click the alert always shows me the last value from the loop for all the buttons i.e length value is being assigned to all the alerts. It isn't assigning independent values for each alert of a button. I have tried several ways like:

element.getElementById('btn' + t).onclick = (this, "onclick", function {
    alert(podObjlen);                    
}); 
element.getElementById('btn' + t).onclick = new function () {
    alert(podObjlen);
}

(Here it shows me proper values in alertbox but i get alert one after the other continously but the alert fails to fire when i actually click a button i.e the alert fires the moment my buttons are rendered. Hope i am being clear. What i want is i need to get the actual value to be assingned to alert of each button when the loop is being run.

RAN
  • 1,443
  • 3
  • 19
  • 30
Adnan Baliwala
  • 463
  • 1
  • 8
  • 12
  • Read up on the concept of Closures :) – Darius Jul 10 '12 at 10:51
  • You're unlucky that the `onclick = (this, "onclick", ...` part is not giving you a syntax error. It's not very meaningful - what do you expect `this` and `"onclick"` to do? – pimvdb Jul 10 '12 at 10:53

1 Answers1

5

Adnan what you are observing is infamous loop problem in javascript. Which occurs due to less understanding around how javascript works it has also been discussed in a previous post here

Javascript infamous Loop issue?

Community
  • 1
  • 1
sushil bharwani
  • 29,685
  • 30
  • 94
  • 128