0

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.

2
  • You need to wrap the string argument in (single) quotes: '{{ item.name }}' With errors like this, always check the source code in the browser first (Ctrl+U). Commented Feb 8, 2020 at 10:36
  • @ChrisG Yes. I should have checked the generated HTML first, I was too focused on the JavaScript part. Commented Feb 8, 2020 at 10:45

1 Answer 1

1

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

<button onclick="addCart({{ item.id }}, {{ item.price }}, {{ item.discount }}, '{{item.name}}')">
               Add to cart
</button>
Sign up to request clarification or add additional context in comments.

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.