Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

184
Visualizações
on click event with JavaScript doesn't work in Django

this is the code for (cart.js) in the static/js folder

var updateBtns = document.getElementsByClassName('update-cart')

for (i = 0; i < updateBtns.length; i++) {
    updateBtns[i].addEventListener('click', function(){
        var productId = this.dataset.product
        var action = this.dataset.action
        console.log('productId:', productId, 'Action:', action)
        
    })
}

and in the HTML file in the bottom:

<button data-product="{{ product.id }}" data-action="add"
                class="update-cart btn btn-outline-secondary add-btn ">Add to Cart</button>

and call the js in main.html

<script type="text/javascript" src="{% static 'js/cart.js' %}"> </script>

and I add static in the setting.py, and everything correct.

and everything working well, when I try to (console.log) without a button click event... the problem is only with the button event because it doesn't work

about 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

Your question is not related to Django. It seems that you do not use JavaScript correctly. When the browser executes code from card.js the HTML DOM tree is not yet built. To attach JS events you need to change cart.js code to:

function initUpdateBtns() {
    var updateBtns = document.getElementsByClassName('update-cart')

    for (i = 0; i < updateBtns.length; i++) {
        updateBtns[i].addEventListener('click', function(){
            var productId = this.dataset.product
            var action = this.dataset.action
            console.log('productId:', productId, 'Action:', action)
        })
    }
}

document.addEventListener('DOMContentLoaded', initUpdateBtns)

about 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda