Ways to retrieve a specific object property from an array of objects within a click event listener?

I have instantiated multiple object constructors and stored them in an array which I loop over to display as a list. Now, I am trying to extract the name property from that list to use in an onclick event handler (not included in this code). I am unsure of how to access the name property within the click handler. Here is what I have attempted so far, but it returns undefined.

console.log(contactarray[i].name);
console.log(contactarray.name);

Code

$(document).ready(function() {

function ContactList (name, email, number, address) {
    this.name = name;
    this.email = email;
    this.number = number;
    this.address = '6539 Wilton Ave Culver City CA 90234';
}

var christian = new ContactList('Christian', '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="99faf1ebf0eaedf0f8f7d9fce1f8f4e9f5fcb7faf6f4">[email protected]</a>', '323-555-124');
var rich = new ContactList('Rich', '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e4968d878ca4819c8589948881ca878b89">[email protected]</a>', '323-555-124');
var scott = new ContactList('Scott', '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d7a4b4b8a3a397b2afb6baa7bbb2f9b4b8ba">[email protected]</a>', '323-555-124');
var danny = new ContactList('Danny', '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c0a4a1aeaeb980a5b8a1adb0aca5eea3afad">[email protected]</a>', '323-555-124');
var taka = new ContactList('Taka', '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5e2a3f353f1e3b263f332e323b703d3133">[email protected]</a>', '323-555-124');
var tim = new ContactList('Tim', '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="82f6ebefc2e7fae3eff2eee7ace1edef">[email protected]</a>', '323-555-124');
var patrick = new ContactList('Patrick', '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="32425346405b515972574a535f425e571c515d5f">[email protected]</a>', '323-555-124');
var jacques = new ContactList('Jacques', '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d6bcb7b5a7a3b3a596b3aeb7bba6bab3f8b5b9bb">[email protected]</a>', '323-555-124');

var contactarray = [christian, rich, scott, danny, taka, tim, patrick, jacques];

for (i = 0; i < contactarray.length; i++) {
    $('#contacts').append('<li class="itemname" id="'+i+'"><a href="#">' + contactarray[i].name + '</a></li>');
}

My challenge lies in accessing the name property of a specific list item when it is clicked.

Answer №1

Encountering the classic issue with asynchronous JavaScript events within a loop is a common occurrence. This issue may not have been immediately apparent from your initial question due to the absence of a click handler, but became evident through your subsequent comment. It's crucial to include sufficient information in your query to accurately replicate the underlying problem. While simplified code can be beneficial, it should not omit the essential problematic area!

An effective solution involves calling a function for each iteration of the loop. When a function is executed, it generates a "closure" that encapsulates all parameters and local variables within that function, even for asynchronous code like a click handler that is invoked later on.

If you are utilizing jQuery, this can be achieved using $.each(), or alternatively, you can devise and call your own function within a for loop, ensuring it is triggered for every loop iteration.

The following represents a functional solution. I made some adjustments to simplify your code by placing the contact items directly within the array rather than creating individual named variables for each one. Additionally, I renamed your ContactList constructor to

ContactItem</code since it denotes a single item as opposed to a list:</p>

<pre><code>function ContactItem( name, email, number,address ) {
    this.name = name;
    this.email = email;
    this.number = number;
    this.address = '6539 Wilton Ave Culver City CA 90234';
}

var contactarray = [
    new ContactItem('Christian', '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="05666d776c76716c646b45607d64687569602b666a68">[email protected]</a>', '323-555-124'),
    new ContactItem('Rich', '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="66140f050e26031e070b160a034805090b">[email protected]</a>', '323-555-124'),
    new ContactItem('Scott', '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4f3c2c203b3b0f2a372e223f232a612c2022">[email protected]</a>', '323-555-124'),
    new ContactItem('Danny', '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4521242b2b3c05203d24283529206b262a28">[email protected]</a>', '323-555-124'),
    new ContactItem('Taka', '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b2c6d3d9d3f2d7cad3dfc2ded79cd1dddf">[email protected]</a>', '323-555-124'),
    new ContactItem('Tim', '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="12667b7f52776a737f627e773c717d7f">[email protected]</a>', '323-555-124'),
    new ContactItem('Patrick', '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b1c1d0c5c3d8d2daf1d4c9d0dcc1ddd49fd2dedc">[email protected]</a>', '323-555-124'),
    new ContactItem('Jacques', '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5933383a282c3c2a193c21383429353c773a3634">[email protected]</a>', '323-555-124')
];

var $contacts = $('#contacts');

$.each( contactarray, function( i, contact ) {
    var $contact = $(
        '<li class="itemname" id="' + i + '">' +
            '<a href="#">' + contact.name + '</a>' +
        '</li>'
    );
    $contact.click( function() {
        alert( contact.name );
    }).appendTo( $contacts );
});

Updated fiddle

Answer №2

Give this a shot

for (let i = 0; i < contactarray.length; i++) {
    $('#contacts').append('<li class="itemname" id="'+i+'"><a href="#">' + contactarray[i].name + '</a></li>');
}

and then try this alternative method

contactarray.forEach(function(contact, id) {
    $('#contacts').append('<li class="itemname" id="'+id+'"><a href="#" onclick="alert(' + contact.name + ')">' + contact.name + '</a></li>');
});

Answer №3

class ContactInfo (name, email, number,address) {
    this.name = name;
    this.email = email;
    this.number = number;
   this.address = '6539 Wilton Ave Culver City CA 90234';
}

window.onload = function() 
{
     var jane = new ContactInfo('Jane', '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4122293328323528202f012439202c312d246f222e2c">[email protected]</a>','');
     var jennifer = new ContactInfo('Jennifer', '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1a687379725a7f627b776a767">[email protected]</a>', '323-555-124');
     var emily = new ContactInfo('Emily', '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0c7f6f6378784c69746d617c6069226f6361">[email protected]</a>', '323-555-');
     var contactList = [jane, jennifer, emily];

     var button = document.getElementById('btn');  

     button.addEventListener('click',function(){
          for (i = 0; i < contactList.length; i++) {
         $('#contacts').append('<li class="itemname" id="'+i+'"><a  href="#">' + contactList[i].name + '</a></li>');
      }
     },false);

}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The emulator failed to launch because it could not find any emulators listed as an output of the `emulator -list-avds` command

Hello everyone, I've recently ventured into the world of React Native and managed to successfully install and launch the emulator. However, I encountered a problem when attempting to run the command react-native run-android. The console output display ...

Filtering a Two-Dimensional Array Using JavaScript

I am working with a basic 2D array that contains x, y coordinates as shown below: var c = [ [1,10], [2,11], [3,12], [4,13], [5,15] ]; I want to know how I can extract pairs from the array that meet specific conditi ...

Steps to retrieve specific text or table cell data upon button click

Greetings, I am a beginner in the world of html and javascript, so please bear with me :) My challenge involves working with a table in html. Each row contains a dropdown menu (with identical options) and a button. When the button is clicked, I aim to sen ...

Contrasting the variance between binding through the [] syntax and abstaining

There is a unique custom my-table element that has its row property bound to the host component. There are two different ways in which HTML can be inserted: <my-table [rows]="displayEntriesCount"></my-table> and alternatively: <my-table r ...

Having trouble with the Semantic UI popup not showing div content correctly? Need to display table row data as well? Let's troub

Having trouble with this semantic-ui code popup error. Can anyone provide a solution? $(document).on('click', 'table td', function() { $(this) .popup({ popup: $('.custom.popup') }); }) ...

Is the fs.watch method being triggered unexpectedly?

As a beginner in node.js and javascript, I've been experiencing an error with the following code snippet: fs.watch('F:/junk', (eventType, filename) => { if(filename && filename.split('.')[1].match("zip")) { ...

What is the best approach to retain a user's selection for dark mode?

I have created a small website to showcase my work, but I'm struggling to figure out how to make the website remember a user's choice of dark mode. After searching on Stack Overflow, I came across suggestions like using cookies or localStorage. ...

Struggling to properly line up the baselines of navigation list items that are styled as circular elements using CSS

I have transformed my navigation menu into a series of CSS circles with text inside. The issue I am facing is that the text spills out unevenly based on the amount of content in each circle. To address this, I used a JavaScript solution to center-align the ...

What is the process for eliminating bower from the current project and implementing requirejs using yarn (newbie perspective)?

Is there a way to switch from using bower in my workflow? After installing yeoman and the knockoutjs generator, I discovered that bower support is limited and bootstrap now uses popper.js, which will no longer support bower in v2. I want to avoid any issu ...

The Spotify Whitelisted URI may show an error message: { "error": "invalid_grant", "error_description": "Redirect URI is invalid" }

Although there are similar questions out there, I'm facing a different issue. I am trying to obtain an access token from Spotify API, but all I keep getting is the dreaded "invalid redirect uri" error. Below is my API call: const request = require(& ...

I am facing an issue where this loop is terminating after finding just one match. How can I modify it to return

I am currently working with an array that compares two arrays and identifies matches. The issue is that it only identifies one match before completing the process. I would like it to identify all matches instead. Can anyone explain why this is happening? ...

Using React to organize and showcase text messages in categorized sections

I am looking to organize text messages into different sections based on when they were received: This includes messages received today, yesterday, this week, this month, and continuing in month intervals as needed... For example: https://i.sstatic.net/R ...

What is the best way to send an array of objects to a Node.js server?

What is the method for sending an array of objects with user data to the server for verification? I am attempting to pass orderform data to a server for validation and then display it on a different page after redirection. const addProductsToServer = (ev ...

Uploading video files using XMLHttpRequest encountered an error on a particular Android device

One of our testers encountered an issue where they failed to upload a video file (.mp4) on a specific Android mobile phone. Interestingly, the same file uploaded successfully on an iPhone and another Android device. To investigate further, I attempted to ...

The Else clause is executing twice in the jQuery code

https://jsfiddle.net/mpcbLgtt/2/ Creating a function that adds card names to an array named deck and their IDs to another array called cardIds when a div with the class "card" is clicked. The cards available are: <div class='card' id=' ...

Automatically tally up the pages and showcase the page numbers for seamless printing

I've been tackling a challenge in my Vue.js application, specifically with generating invoices and accurately numbering the pages. An issue arose when printing the invoice – each page was labeled "Page 1 of 20" irrespective of its actual position in ...

Tips for delivering a heartfelt message when a user adds an item

import React from 'react'; import { useForm } from "react-hook-form"; import { toast } from 'react-toastify'; const AddStorage = () => { const { register, handleSubmit } = useForm(); const submitData = data => ...

Posting values using AJAX in PHP - A guide

test.html <html> <!-- To access the complete PHP-AJAX tutorial, please visit http://www.php-learn-it.com/tutorials/starting_with_php_and_ajax.html If you found this tutorial helpful, a backlink to it would be greatly appreciated. ...

Using the MoveToElement and click functions in Protractor with Node.js for automated browser

Trying to click on a checkbox in our application. I have successfully implemented it in Selenium Java using the code below, but struggling to do the same in Protractor Node.js. Any assistance would be appreciated. Selenium- Java : Actions actions ...

Commitments and incorporating items from an array into objects nested within a separate array

My current project involves a command line node application that scrapes valuable data from a specific website and stores it in a CSV file. For the scraping functionality, I am utilizing scrape-it, which enables me to successfully extract all the necessa ...