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.