LaVOZs

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 => {
console.log(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
    ? friend[i].picture
    : $("#rpic").attr(
        "src",
        "https://icons-for-free.com/iconfiles/png/512/business+costume+male+man+office+user+icon-1320196264882354682.png"
      );
  $("#cardcontainer").append(html2);
  $(".ui.basic.green.button").click(i => {
    console.log("hello");
    var data = { data: friend[i] };

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

$(".ui.basic.green.button") to $(".ui.basic.green.button")[i].

Hope it helps !!

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

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

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

Related
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