0

I have an array of contacts in a JSON object however the variable that displays in the .on('click'...) event is always the last item in the JSON array.

The <a> id is set correctly but the alert always returns the last contactID in the JSON array

Is there something in my code that is wrong....?

  var theDIV = $('#1234DIV');
  for (var i=0;i<theJSON.contacts.length;i++) {
    var theContact = theJSON.contacts[i];
    var contactID = theContact.contact_id;

    var theLink = $('<a>',{
      'id': 'Acontact_'+contactID,
      'href':'javascript:;',
    }).on('click', function(event) {
      console.log(event);
      console.log(contactID);
      alert(contactID);
    }).html(theContact.name_display);

    theDIV.append(theLink);
  }

Here is the JSON example:

 {"result_count":2,"contacts":[{"contact_id":"508","name_display":"George Washington","flag_type":"contact","name_title":"","name_first":"George","name_last":"Washington"},"contact_id":"716","name_display":"Red","flag_type":"contact","name_title":"","name_first":"Red","name_last":"Shawshank"}]}
Tim Wiel
  • 55
  • 11

2 Answers2

0

Hey Tim, you're overwriting the value of contactID on each iteration of your loop, so there is only one "contactID" and it will be whatever was the last in your json.

A couple of things.

You don't need to attach a individual click action on each new <a> tag you generate. Give each one a specific class name such as "button", and then use

$('body').on('click', '.button', function (){
        alert( $(this).data("contactID") );
});

By attaching this to the body, it will catch all newly created a.button elements.

Then in your loop do

var theLink = $("<a>", {
    'id': 'Acontact_'+contactID, 
    'class': "button"
}).html(theContact.name_display).data("contactID", contactID);
$("#box").append(theLink);
Mr Lister
  • 45,515
  • 15
  • 108
  • 150
Alex
  • 1,535
  • 2
  • 16
  • 26
0

The correct way to do it I discovered was (with jQuery) with the $.each() function:

  var theDIV = $('#1234DIV');
  $.each(theJSON.contacts, function (index, contact) {
    var theContact = theJSON.contacts[i];
    var contactID = theContact.contact_id;

    var theLink = $('<a>',{
      'id': 'Acontact_'+contactID,
      'href':'javascript:;',
    }).on('click', function(event) {
      console.log(event);
      console.log(contactID);
      alert(contactID);
    }).html(theContact.name_display);

    theDIV.append(theLink);
  }

And it works!!

Tim Wiel
  • 55
  • 11