title: jQuery/JavaScript assign click event in loop (closures?)
body: <blockquote>
    <p><strong>Possible Duplicate:</strong><br>
    <a href="https://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example">Javascript closure inside loops - simple practical example</a>  </p>
  </blockquote>
  
  
  
  <p>I'm creating a table of statuses for a "dashboard" web page. Each status is in a state of "On" or "Off".</p>
  
  <p>I'm trying to use the jQuery <code>button/buttonset</code> to have switch/toggle controls to allow the user to toggle the value of a status. I create the table and buttons dynamically as the result of an ajax database query.</p>
  
  <p>I'm basically trying to fire off an ajax query when the user clicks on one of the buttons, but I'm struggling to assign the click event properly.</p>
  
  <p>My first go-round had the final list value fire no matter what button was clicked. </p>
  
  <p>Therefore, Aha! It's a standard "JavaScript closure" issue. (So I thought...)</p>
  
  <p>Further playing around with it has yielded nothing, and I don't really understand the closure issue well enough to figure out why my technique is wrong.</p>
  
  <p>Here's the code I want to call:</p>
  
  <pre><code>function SetStatus(item, status) {
      var params = '{itemName: "' + item + '", status: "' + status + '"}';
      $.ajax({
          type: "POST",
          url: "WebServices/Dashboard.asmx/SetItemStatus",
          data: params,
          contentType: "application/json; charset=utf-8",
          dataType: "json",
          success: StatusSet,
          error: ShowError
      });
  }
  </code></pre>
  
  <p>Here's the current version of code I'm trying:</p>
  
  <pre><code>$(itemOnButton).click(
      function (_item) {
          SetStatus(_item, 'On');
      } (itemName)
  );
  </code></pre>
  
  <p>The result is that immediately upon getting the results from the database (before they're even displayed), <code>SetStatus</code> fires for the last item with <code>status</code> == 'On'.</p>
  
  <p>I know this is simple, and I'm still convinced it's a basic closure issue, but I'm banging my head against the wall! Thanks for any help!</p>