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

Struggling to retrieve unpredictable data in a Vue.js component

Help! I'm trying to randomly display one of these names in my HTML, but I can't seem to make it work: Vue.component('modal', { template: '#modal-template', data: { items: [ { name: 'Elena' }, { na ...

unable to display the responseJson findings

I'm having trouble understanding why this function for an API on National Parks isn't working as expected. As a relatively new programmer, I find that seeking help from others can often shed light on issues I may have missed. Any assistance woul ...

Firefox not clearing Highcharts points properly

I am currently utilizing highcharts to generate dynamic charts when hovering over a table row. My goal is to clear and hide the chart once the mouse moves away from the row. While this functionality works smoothly in Chrome, I am encountering a strange is ...

Is it possible to substitute a one-line jQuery.load() with a fetch() function that achieves the same result?

I am currently working on a page where I utilize a single line of jQuery code: $('#id').load('/url'); This line allows me to load a fragment into a specific place in the DOM. However, I am now considering reducing my reliance on jQuer ...

Ui-router experiencing issues with nested view loading due to changes in URL

I have been developing an application and previously used ui-router successfully with Ionic. The issue I am facing now is that although the URL changes correctly as expected, nothing happens afterwards. I am certain that the template is being found because ...

What methods can be utilized to avoid displaying a Bootstrap popover intermittently within an AngularJS framework?

When using the bootstrap popover in a custom AngularJS directive, I need to display an error message when the button is disabled by setting $scope.buytypeButton= {type:false}. The error message should be displayed in a popover. On the other hand, when $sco ...

ui-grid row size set to automatically adjust using rowHeight : 'auto'

Has anyone else experienced this strange behavior with ui-grid? When I set the rowHeight to auto, each cell in the same row ends up with different heights. One of the cells contains multiline data, which seems to be causing issues for ui-grid. I've ev ...

Creating an editable list item with jQuery: A step-by-step guide

I am trying to create a user-friendly interface where users can view and edit their information in a listview. The data will be retrieved from a database and displayed in the listview. My goal is to make the listview editable, so when a user clicks on it ...

Troubleshooting Problems with CSS Three-Column Layout

Struggling with aligning domain names in a 3 column setup, I have been attempting this for some time now without success. I am new to this and could use some guidance. Here is the code: TPL file <div> <p class="center">{foreach key=num it ...

Flexslider doesn't adjust the height of the viewport when displaying a shorter image in the slideshow

Is Flexslider not resizing its viewport height according to the current image on your site? The fixed height seems to be causing blank white space under shorter images. Are you inadvertently overriding Flexslider's responsive height function? Is there ...

What is the correct method to implement the jQuery document ready event?

When it comes to writing the document ready event in jQuery, there are several methods available. Which of the following syntax options would be considered the most correct way to write the document ready event, and why? 1) jQuery(document).ready(functi ...

What is the maximum number of groupings that can be created from a set of numbers within a

I'm trying to figure out how to handle a specific task, but I'm running into some obstacles. When adding numbers to clusters, a number is considered to belong to a cluster if its distance to at least one existing number in the cluster is within a ...

Using PHP's for loop to iterate through data and store them into arrays

Attempting to transmit data from JavaScript to a PHP file through an AJAX request, and then store each result in an array using PHP. queryData={"data":{"data_string":{"data":"medicine","default_field":"Content"}}} testArgument=0; $.ajax({ url:"test/q ...

What is the mechanism of `this` in higher order components?

I am delving into the concept of higher order components by exploring this online resource. However, I am struggling to grasp how this is utilized within one. Am I correct in thinking that the this in the constructor refers to what will ultimately be retur ...

Button click not triggering Ajax functionality

I've been working on implementing a simple Ajax function in a JSP using JQueryUI. The goal is to pass two text fields from a form and use them to populate two separate divs. However, when I click the button, nothing seems to be happening. I even tried ...

Multiple Ajax requests being made

Below is the code snippet in question: <div id="assignWindow" style="display:none; width:500px"> Invoice # <input id="invoiceNumber" name="invoiceNumber" /><br /> Amount: <input id=" ...

How can we use Python and Selenium to retrieve the text from HTML that includes the <p> tag?

I have a simple question that I hope you can help me with. I'm not feeling well and struggling to complete my presentation because my brain just isn't functioning properly. Here is the HTML code in question: <p> <b>Postal code:& ...

Notification for Unsuccessful Login Attempt on the Client Side

In my node.js project, I have implemented a login form that sends data to the server.js file as URL parameters. When the sent data is verified against registered users, the client is successfully logged in. However, I am facing an issue on how to notify th ...

Updating the title of a page on CoreUI's CBreadcrumbRouter dynamically

I'm currently developing a project with VueJS and the CoreUI admin template. Is there a way I can change the title of the current page as shown on the CBreadcrumbRouter? The GitHub documentation mentions that the script typically displays meta.label ...

Uncovering the secrets of locating and deleting arrays with the power of jQuery

Is there a way to extract data from an array list and then have it automatically removed once displayed? let fruits = ["Banana", "Orange", "Watermelon"]; For instance, if I want to select the Watermelon element from the array. After retrieving and display ...