I have some data attributes on buttons that I need to send as content to a div when those buttons are clicked. A part of my code until now is this:
function getDiscount() {
var buttons = document.querySelectorAll(".form-button");
buttons.forEach(function(item, index) {
item.addEventListener('click', function() {
var discount = getDiscount(this);
});
});
function getDiscount(clicked_element) {
var val = clicked_element.getAttribute("data-discount");
return val;
}
};
<div class="discount__Topics">
<div><strong class="discount-amount">50</strong>%</div>
<div class="offers">
<button class="form-button" data-discount="38">Offer 1</button>
<button class="form-button" data-discount="50">Offer 2</button>
<button class="form-button" data-discount="22">Offer 3</button>
<button class="form-button" data-discount="88">Offer 4</button>
</div>
</div>
<div class="discount__Topics">
<div><strong class="discount-amount">60</strong>%</div>
<div class="offers">
<button class="form-button" data-discount="12">Offer 1</button>
<button class="form-button" data-discount="32">Offer 2</button>
<button class="form-button" data-discount="44">Offer 3</button>
<button class="form-button" data-discount="55">Offer 4</button>
</div>
</div>
I'm just not seeing how to change the html with attribute when it's clicked and how to have two sets of buttons or more on the same page.
Hope someone can help. Many thanks
UPDATE: Now the code is running properly but im having troubles with getting multiples div's with multiple buttons working. I've created a for.Each wic logs my div correctly but im not beeing able to have the working properly.
var discounters = document.querySelectorAll(".discount__Topics");
discounters.forEach((index) => {
console.log(index)
var buttons = document.querySelectorAll(".form-button");
buttons.forEach(function (item) {
item.addEventListener('click', function(){
var discount = getDiscount(this);
let span = document.querySelector('.discount-amount')
span.innerHTML = '<strong>' + discount+ '</strong>'
});
});
function getDiscount(clicked_element) {
var val = clicked_element.getAttribute("data-discount");
return val;
}
});
<div class="discount__Topics">
<div><strong class="discount-amount">38</strong>%</div>
<div class="offers">
<button class="form-button" data-discount="38">Offer 1</button>
<button class="form-button" data-discount="50">Offer 2</button>
<button class="form-button" data-discount="22">Offer 3</button>
<button class="form-button" data-discount="88">Offer 4</button>
</div>
</div>
<div class="discount__Topics">
<div><strong class="discount-amount">12</strong>%</div>
<div class="offers">
<button class="form-button" data-discount="12">Offer 1</button>
<button class="form-button" data-discount="32">Offer 2</button>
<button class="form-button" data-discount="44">Offer 3</button>
<button class="form-button" data-discount="55">Offer 4</button>
</div>
</div>
spanelement with astrongtag.