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"}]}
1
  • 1
    Check this link Commented Sep 8, 2016 at 3:57

2 Answers 2

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!!

Sign up to request clarification or add additional context in comments.

Comments

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);

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.