Skip to content
Advertisement

Execute Javascript code on HTML button click

I’m currently making an eshop. I use cookies to store the shopping cart.

This is my HTML button:

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

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

And when the user clicks this button I want to execute the following Cart.js code, which simply creates a cookie and add the product id to cookie cart.

//here i set the cart cookie
function getCookie(name) {
    //split string and get all induvidual name=value pairs in array
    var cookieArr = document.cookie.split(';');
    //loop though array elements
    for (var i = 0; i < cookieArr.length; i++) {
        var cookiePair = cookieArr[i].split("=");

        //removing whitespace at the beginning of the cookie name and compare it with the given string
        if (name == cookiePair[0].trim()) {
            //decode cookie value and return
            return decodeURIComponent(cookiePair[1]);
        }
    }
    //return null if not found
    return null;
}

var cart = JSON.parse(getCookie('cart'));
if (cart == undefined) {
    cart = {}
    console.log("cart was created")
    document.cookie = "cart=" + JSON.stringify(cart) + ";domain=;path=/"
}
console.log("cart:", cart);


//and here i take action when the html button gets a click
var updateBtns = document.getElementsByClassName('update-cart')

for (var i = 0; i < updateBtns.length; i++) {

    updateBtns[i].addEventListener('click', function () {
            var productId = this.dataset.product
            var action = this.dataset.action
            console.log('product id:', productId, 'action:', action)
            addCookieItem(productId, action)
        
    })

}

function addCookieItem(productId, action) {
    console.log('Not logged in...')

    if (action == "add") {
        if (cart[productId] == undefined) {
            cart[productId] = { 'quantity': 1 }

        }
        else {
            cart[productId]['quantity'] += 1
        }
    }

    if (action == "remove") {
        cart[productId]['quantity'] -= 1

        if (cart[productId]['quantity'] <= 0) {
            console.log("remove item")
            delete cart[productId]
        }

    }
    console.log("Cart=", cart)
    location.reload()
    document.cookie = "cart=" + JSON.stringify(cart) + ";domain=;path=/"


My problem is that when I click the button it takes no action. What is wrong?

Advertisement

Answer

Click handler is missing.it should be like this

<button onclick="addCookieItem(product.id,'add')" data-product={{product.id}} data-action = "add" class="btn btn1 btn-primary update-cart">Add to cart</button>
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement