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 >
<div><strong >50</strong>%</div>
<div >
<button data-discount="38">Offer 1</button>
<button data-discount="50">Offer 2</button>
<button data-discount="22">Offer 3</button>
<button data-discount="88">Offer 4</button>
</div>
</div>
<div >
<div><strong >60</strong>%</div>
<div >
<button data-discount="12">Offer 1</button>
<button data-discount="32">Offer 2</button>
<button data-discount="44">Offer 3</button>
<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
CodePudding user response:
You have defined two functions called getDiscount
, it would be better to let them have different name
function init(){
var buttons = document.querySelectorAll(".form-button");
buttons.forEach(function (item, index) {
item.addEventListener('click', function(){
var discount = getDiscount(this);
let span = document.querySelector('.discount-amount')
span.innerHTML = '<strong>' discount '</strong>%'
//span.innerHTML =discount.bold() '%' // we can use bold() instead
});
});
function getDiscount(clicked_element) {
var val = clicked_element.getAttribute("data-discount");
return val;
}
};
init()
<div><span ><strong>55</strong>%</div>
<div >
<button data-discount="38">Offer 1</button>
<button data-discount="50">Offer 2</button>
<button data-discount="22">Offer 3</button>
<button data-discount="88">Offer 4</button>
</div>
CodePudding user response:
If I understand your question correctly, you are looking for something like this.
var buttons = document.querySelectorAll(".form-button");
var discountRef = document.querySelector(".discount-amount");
function setDiscount(pointerEvent) {
// get the clicked button from the pointerEvent
var discount = pointerEvent.target.dataset.discount
// add the discount to <span ></span>
discountRef.innerText = discount
}
buttons.forEach(function (item) {
item.addEventListener('click', setDiscount);
});
Let me know if this helped you out!