I am writing a website where I show certain items (from the game). Info about market names of these items are retrieved from third-party API. Next step is that for every item, there is created div that contains market name of the item. There could be situations where there are two or more div's containing same text values such as "Item 1" and "Item 1". And it is perfectly fine situation. Website also allows to highlight relevant items (click on a div). There is also "Confirm" button. After clicking it, there is generated confirmation dialog that shows names of highlighted items. The issue is that when there are two div's with same text values selected, confirmation dialog does not show these repeated text values at all.
`<script>
$(document).ready(function() {
var selectedSkins = [];
$('.market-names').on('click', '.market-name', function() {
$(this).toggleClass('highlighted');
var marketName = $(this).text();
// Add or remove the market name from the selected skins array
var index = selectedSkins.indexOf(marketName);
if (index === -1) {
selectedSkins.push(marketName);
} else {
selectedSkins.splice(index, 1);
}
});
$('#confirm-button').on('click', function() {
if (selectedSkins.length > 0) {
var itemCounts = {};
// Count the occurrences of each item name
selectedSkins.forEach(function(skin) {
if (itemCounts.hasOwnProperty(skin)) {
itemCounts[skin]++;
} else {
itemCounts[skin] = 1;
}
});
var confirmationContent = "<h3>Confirmation</h3>";
confirmationContent += "<ul>";
// Iterate over the selected item names
Object.keys(itemCounts).forEach(function(skin) {
// Display the item name with the count if it occurs more than once
if (itemCounts[skin] > 1) {
confirmationContent += "<li>" + skin + " (x" + itemCounts[skin] + ")" + "</li>";
} else {
confirmationContent += "<li>" + skin + "</li>";
}
});
confirmationContent += "</ul>";
confirmationContent += "<button id='close-button'>Close</button>";
// Create and display the confirmation dialog
var confirmationDialog = $('<div>').addClass('confirmation-dialog').html(confirmationContent);
$('body').append(confirmationDialog);
// Handle the close button click event
$('#close-button').on('click', function() {
confirmationDialog.remove();
});
}
});
});
</script>`