0

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

2 Answers 2

2

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)

Sign up to request clarification or add additional context in comments.

2 Comments

working , thanks, actually i followed a video, and he made it like what I did, and it is working in his case, I have his source code from GitHub, but I don't know what is the different
No problem. Original code can work too, in some cases, depending on a browser etc. But with document.addEventListener('DOMContentLoaded', ... it should work almost always, at least in all modern browsers.
0

I might be late to answer this question, but it might help someone in the future.

Solution: Make sure your script tags:

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

is between the body tags

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.