The World’s Largest Online Community for Developers

'; javascript - Onclick inside of loop clicking all elements - LavOzs.Com

I got some data from an ajax and loop through it to make cards. I have an onclick inside my loop. the on click is supposed to grab the data object of the index, but everytime I click first element, it grabs all the objects from the array. I've tried changing my for loop to a for each moving the function outside the loop and binding "this" to it but to no avail. any help?

enter code here $.ajax({
url: "/user",
method: "POST" }).then(res => {
let friend = res.request;
for (i = 0; i < friend.length; i++) {
  var html2 =
    "<div class='ui card'><div class='card' id='rcard'> <div class='content'> <img class='right floated mini ui image' id='rpic' src = '" +
    friend[i].picture +
    "<div class='header'>" +
    friend[i].username +
    "</div><div class='meta'>" +
    friend[i].Email +
    "</div><div class='description'>" +
    friend[i].username +
    "  would like to be your friend </div></div><div class='extra content'><div class='ui two buttons'><div class='ui basic green button' id='accept'>Approve</div> <div class='ui basic red button' id='decline'>Ignore</div></div> </div></div>";
    ? friend[i].picture
    : $("#rpic").attr(
  $("").click(i => {
    var data = { data: friend[i] };

As you are using $("") it gets all elements on the page having this class. So in your code try changing

$("") to $("")[i].

Hope it helps !!

$("") grabs all elements on your page having selector, it is not restricted to the element of the loop.

So at each loop, you map click() for ALL of your page.

So, when you press the button, as it's mapped to all objects, they all execute.

How do I detect a click outside an element?
How do I check if an element is hidden in jQuery?
Deleting an element from an array in PHP
How do I loop through or enumerate a JavaScript object?
JavaScript closure inside loops – simple practical example
How to replace all occurrences of a string?
How to move an element into another element?
Loop through an array in JavaScript
How do I remove a particular element from an array in JavaScript?
jQuery scroll to element