views:

73

answers:

1

Hi, basically I'm trying to pass a variable that is defined in a JSON array that is parsed through in a for loop to be accessible in a click statement.

$(document).ready(function() {
  getJSON();
  var usedID;
 });
 function readJSON() {
  for (var i = 0; i < json.array.length; i ++) {
  usedID = json.array[i].id;
  var template = $('repeaterTemplate').clone();
  template.removeAttr('id');
  template.attr('id', 'k' + json.array.id);
  var omega = json.array.id;        
  $('#repeater').append(template);
  (function(o) {
     $('#' + o).click(function() {
    // this is where the submitID click function is now. It passes the omega value in

  });
  })(omega);

 }
 }
 $('.submitID').click(function() {
    submitNow(usedID);
  }

Right now I have the submitID click function in my for loop and it's causing the submitNOW function to be called however many times the loop cycles through. Can anyone help me with passing the userID from the readJSON() to the click function?

I'm getting a parse error with your each function:

var userID = [];
var j = 0;
$('.submitNOW').each(function() {
   function(id) {
$(this).click(function() {
  submitNow(id);
});
  }(userID[j]);
});
A: 

I think you're trying to do something like this but you don't have any way to associate a specific user id with a specific element.

this example gives user id's in the order they are encountered to .submitID elements in the order that they are encountered. it also assumes there are the same number of user id's and elements.

/* this is a non-working example */

var usedIDs = [];

function readJSON() {
    for (var i = 0; i < json.array.length; i++) {
        usedIDs.push(json.array[i].id);
        moreFunctions();
        moreStuff();
    }
}

var j = 0;

$('.submitID').each(function () {

    function (id) {
        $(this).click(function () {
            submitNow(id);
        });
    }(usedIDs[j]);

    j++;

});

edits: based on your post revision this is my best guess at what you are trying to do.

function readJSON() {

    for (var i = 0; i < json.array.length; i++) {

        var usedID = json.array[i].id;

        var template = $('repeaterTemplate').clone();
        template.removeAttr('id');
        template.attr('id', 'k' + usedID);
        $('#repeater').append(template);

        (function (o) {
            // assumign template is a jQuery object here; if not use $(template) instead
            template.click(function () {
                // this is where the submitID click function is now. It passes the omega value in 
                submitNow(o);
            });
        })(usedID);

    }
}
lincolnk
hey, look at my code example up top. I'm getting a parse error with your example each function
fordays
@fordays missing `)` before `(userID[j]);` keep your cool! :)
sandeepan