Chandan Mahto
Chandan Mahto

Reputation: 147

Syntax error while passing arguments to JavaScript function from Django template

I have to pass 4 arguments from a Django template to a JavaScript function. Out of these 4, 3 are integers/decimals and 1 is a string.

<button onclick="addCart({{ item.id }}, {{ item.price }}, {{ item.discount }}, {{item.name}})">
               Add to cart
</button>

Here is the Javascript function.

let USER_CART = [];
function addCart(itemId, itemPrice, itemDiscount, itemName) {
    let itemQuantity = parseInt(document.getElementById(itemId).value);
    if (itemQuantity > 0) {
        let item_index = USER_CART.findIndex(item => item.id === itemId);
        if (item_index === -1) {
            let item = {
                id: itemId,
                price: itemPrice,
                discount: itemDiscount,
                quantity: itemQuantity,
                title: itemName,
            };
            USER_CART.push(item);
        } else {
            USER_CART[item_index].quantity += itemQuantity;
        }
    }
}

Whenever I click on the button this error shows up on the console.

SyntaxError: missing ) after argument list

Another interesting thing is if I remove the item.name and itemName completely from the code, it works just fine.

Upvotes: 0

Views: 97

Answers (1)

Nafees Anwar
Nafees Anwar

Reputation: 6598

You need to add quotes around {{item.name}}.

<button onclick="addCart({{ item.id }}, {{ item.price }}, {{ item.discount }}, '{{item.name}}')">
               Add to cart
</button>

Upvotes: 1

Related Questions