JS How can I generate individual buttons in a loop that trigger separate actions?

Currently, I am working with loops in jQuery to create a series of boxes that contain specific values.

The problem arises when I try to assign actions to each box based on the values from an array. For example, I want each box to trigger a different alert when clicked.

This is the code snippet I have been using:

var sampleData = [
{ category: "Material", id: 'Code0-1', name: 'Machine breakdown' },
{ category: "Material", id: 'Code0-1', name: 'Machine breakdown' },
{ category: "Tool", id: 'Code0-1', name: 'Machine breakdown' },
{ category: "Tool", id: 'Code0-1', name: 'Line breakdown' },
{ category: "Tool", id: 'Code0-1', name: 'Machine breakdown' },
{ category: "Tool", id: 'Code0-1', name: 'Line breakdown' },
{ category: "Tool", id: 'Code0-1', name: 'Machine breakdown' },
{ category: "Tool", id: 'Code0-1', name: 'Line breakdown' }
];

$.each(sampleData, function (i) {
var templateString = '<article class="card"><h2>' + sampleData[i].category + '</h2><p>' + sampleData[i].name + '</p><p>' + sampleData[i].id + '</p><button class="test">Start</button></article>';
    $('#favoriteCards').append(templateString);
});

$(".test").on("click", function () {
    alert("Click");
});
.cards {
    margin: -1rem;
}

.card {
    width: 220px;
    float: left;
    margin: 1rem;
    border: 1px solid #d3d3d3;
    padding: 20px;
    border-radius: 5px;
    background-color: white;
}

@supports (display: grid) {
    .cards {
        margin: 0;
    }

    .cards {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
        grid-gap: 1rem;
    }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<main class="cards">
    <div id="favoriteCards"></div>
</main>

Although I've assigned an action to the button, it does not work as expected because I want each button to trigger a unique alert message based on the data from the array.

Answer №1

To customize an element and receive data alerts, add a custom attribute(data-*) to the element. You can then retrieve this data whenever needed. Additionally, when using the jQuery.each callback function, consider utilizing the second argument as a parameter for the element instead of relying on index-based retrieval.

var sampleData = [{"category":"Material","id":"Code0-1","name":"Machine Breakdown"},{"category":"Material","id":"Code0-1","name":"Machine Breakdown"},{"category":"Tool","id":"Code0-1","name":"Machine Breakdown"},{"category":"Tool","id":"Code0-1","name":"Line Breakdown"},{"category":"Tool","id":"Code0-1","name":"Machine Breakdown"},{"category":"Tool","id":"Code0-1","name":"Line Breakdown"},{"category":"Tool","id":"Code0-1","name":"Machine Breakdown"},{"category":"Tool","id":"Code0-1","name":"Line Breakdown"}];

$.each(sampleData, function() {
  var templateString = '<article class="card"><h2>' + this.category + '</h2><p>' + this.name + '</p><p>' + this.id + '</p><button class="alertTarget" data-alert="' + this.name  + '">Start</button></article>';
  $('#favoriteCards').append(templateString);
});

$(".alertTarget").on("click", function() {
  alert($(this).data('alert'));
});
.cards {
  margin: -1rem;
}

.card {
  width: 220px;
  float: left;
  margin: 1rem;
  border: 1px solid #d3d3d3;
  padding: 20px;
  border-radius: 5px;
  background-color: white;
}

@supports (display: grid) {
  .cards {
    margin: 0;
  }
  .cards {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
    grid-gap: 1rem;
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<main class="cards">
  <div id="favoriteCards"></div>
</main>

Answer №2

If you're looking to display different content for each card, follow this method.

var customData = [
{ category: "Material", id: 'Code0-1', name: 'Breakdown of machine' },
{ category: "Material", id: 'Code0-1', name: 'Breakdown of machine' },
{ category: "Tool", id: 'Code0-1', name: 'Breakdown of machine' },
{ category: "Tool", id: 'Code0-1', name: 'Breakdown of line' },
{ category: "Tool", id: 'Code0-1', name: 'Breakdown of machine' },
{ category: "Tool", id: 'Code0-1', name: 'Breakdown of line' },
{ category: "Tool", id: 'Code0-1', name: 'Breakdown of machine' },
{ category: "Tool", id: 'Code0-1', name: 'Breakdown of line' }
];

$.each(customData, function (i) {
var templateString = `<article class='card ${i}'><h2>` + customData[i].category + '</h2><p>' + customData[i].name + '</p><p>' + customData[i].id + i + '</p><button class="tes">Start</button></article>';
    $('#favoriteCards').append(templateString);
});


let document = document.querySelectorAll(".card");
document.forEach((x)=> x.addEventListener("click",function(){
  alert(x.className);
}))
  .cards {
    margin: -1rem;
}

.card {
    width: 220px;
    float: left;
    margin: 1rem;
    border: 1px solid #d3d3d3;
    padding: 20px;
    border-radius: 5px;
    background-color: white;
}

@supports (display: grid) {
    .cards {
        margin: 0;
    }

    .cards {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
        grid-gap: 1rem;
    }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <main class="cards">
      <div id="favoriteCards"></div>
  </main>

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

Discovering how to adjust the "border-spacing" in a React Material-UI Table to ensure each row is nicely separated

I am looking to create Material-UI Collapsi Table Rows with separate styling. Check out the link for more information: https://material-ui.com/components/tables/#CollapsibleTable.tsx const theme = createMuiTheme({ overrides: { MuiTable: { root ...

Is it possible to securely share login details on the internet?

I'm currently brainstorming different ways to securely display FTP, database, and hosting information for website projects on my project management site. One potential solution I'm considering is encrypting the passwords and developing an applica ...

Creating a dynamically sorting page for displaying products by utilizing a combination of PHP, AJAX, jQuery, and a dropdown menu

I'm currently working on implementing a dropdown menu that allows users to sort a page by "price high-low" or "price low-high". Below is the HTML code with an ID of "show_product": <div class="row" id ="notification-bar"></div> <div c ...

Here is a unique rewrite: "Strategies for effectively passing the data variable in the geturldata function within Vue.js on the HTML side vary

How can I properly pass a variable in the getdataurl function in Vue.js? I need help with passing a variable in getdataurl function in Vue.js. Please provide a clear explanation and include as much detail as possible. I have tried doing some background r ...

"Utilizing Promises in AngularJS Factories for Synchronous API Calls

Attempting to implement synchronous calls using a factory pattern. $scope.doLogin = function (username, password, rememberme) { appKeyService.makeCall().then(function (data) { // data = JSON.stringify(data); debugAlert("logi ...

When the window is scrolled to 50%, I would like to load some additional data

Looking to load data when the browser scrollbar reaches 50%... In jQuery, I created the following function: $(window).on('scroll', function () { alert("scrolling"); if ($(window).scrollTop() + $(window).innerHeight() > ...

including information inputted into a form into a data-storage system

I have set up a webform for users to request access to my CV. After submission, I aim to save their details in a phpMyAdmin database. As a PHP beginner handling databases within an HTML file, I received some code that needed modifications to fit my form fi ...

Is PHP not being called by AJAX?

Could someone please assist me in identifying where I am going wrong? My goal is to make a PHP call when a selected value is changed. The code is not displaying the information from the PHP file. JQUERY CODE // Skill sort on change $('#order_by&apo ...

The output is: [object of type HTMLSpanElement]

<form> <table> <tr> <td>Distance:</td> <td><input type="number" id="distance" onKeyUp="calculate();">m</td> </tr> <tr> <td>Time:</td> ...

Jumping Iframe Anchor Link in Src

I'm facing a challenge with an iframe positioned in the center of a webpage. I want to show content from another page within the iframe, but not starting at the very top. To achieve this, I inserted an anchor into the src of my iframe, linked to an a ...

Steps to develop a collaborative NPM package

I am currently in the process of developing an NPM package using Typescript that contains solely my type interfaces. At the moment, my project has the following folder structure: project │ index.ts │ └───types │ restaurant.ts │ ...

Arrange JSON data in ascending order based on the dates, starting with the most recent date, by utilizing jquery

I'm in need of assistance on sorting a list of articles from an external json file based on their creation date. Can anyone provide guidance? Currently, I am fetching the data using AJAX and displaying only 6 results, but I'm facing difficulties ...

Issue encountered in ../../../../ Unable to locate namespace 'Sizzle'

Following the execution of npm install @types/jquery, I encountered a compilation issue while running my Angular project with ng serve ERROR in ../../../../../../AppData/Roaming/JetBrains/WebStorm2020.1/javascript/extLibs/global-types/node_modules/@types/j ...

Indeed, verification of an array - values are mandatory only when the array exceeds a length of 1

In my form, each row contains 2 dropdowns and I have the ability to dynamically add or remove rows except for the first one. My goal is to allow form submission only if there is one pre-rendered empty row, otherwise the form should not be able to submit if ...

Issue with facebook button in reactJS where onClick() event is not being triggered

I'm facing an issue where my onClick handler is not working with the Facebook button from https://developers.facebook.com/docs/facebook-login/web/login-button/. However, it works fine with a regular div element. Any thoughts on why the onClick event ...

There seems to be a glitch in my programming that is preventing it

Can someone please help me troubleshoot this code? I'm unable to figure out what's going wrong. The concept is to take user input, assign it to a variable, and then display a string. However, nothing appears on the screen after entering a name. ...

How to disable the Rubber/Elastic scrolling feature on your iPad?

On my webpage, there is a combination of vertical and horizontal scrolling. Everything works fine when the user swipes left or right exactly, but issues arise when the swipe is not precise along a straight line (diagonally). In this case, both vertical and ...

Generate text in reStructuredText with columns

I'm attempting to style a reStructuredText segment in the following layout: type1 : this type4 : this type7 : this type2 : this type5 : this type8 : this type3 : this type6 : this type9 : this I want to fill the page with tex ...

Deactivate input areas while choosing an option from a dropdown menu in HTML

I've been working on creating a form and have everything set up so far. However, I'm looking to disable certain fields when selecting an option from a dropdown list. For instance, if the "within company" option is selected for my transaction typ ...

What is the best way to restrict a React input field to have values within the minimum and maximum limits set by its

As a newcomer to React, I am working on restricting my input to values between -10 and 10. Currently, the input is set up to accept any value, and I am utilizing hooks like useState and useEffect to dynamically change and set the input value. My goal is ...