Reputation: 17
<!-- Any html blocks -->
{% for n in loop %}
<div class="update">
<div>
<button type="button" class="update--btn">-</button>
</div>
</div>
{% endfor %}
let updateBtn = document.getElementsByClassName('update--btn');
[...updateBtn].forEach(e => {
e.addEventListener('click', clickBtn);
})
function clickBtn() {
const xhr = new XMLHttpRequest();
xhr.open('POST', url);
xhr.onload = () => {
let cartUpdate = this.closest('.update');
cartUpdate.innerHTML ='';
let cartUpdateInner = document.createElement('div');
cartUpdateInner.innerHTML = '<button type="button" class="update--btn">+</button>'
cartUpdate.appendChild(cartUpdateInner);
}
xhr.send();
}
When the page is loaded for the first time, all working. But second click on button, after change HTML in not working.
PS. I need change html, not only text
Upvotes: 0
Views: 689
Reputation: 119
you can put your update button code in a function like
function addevent(){
[...updateBtn].forEach(e => {
e.addEventListener('click', clickBtn);
})
}
and then call it on page load for first time
window.onload = addevent;
and then you need to reassign this event after adding new buttons so you can call this in the end of your clickBtn function
addevent()
Upvotes: 1