Why is the Javascript Ecommerce add to cart feature failing to work properly?

I've been working on implementing an add to cart feature using a combination of Javascript and Django, with the main functionality relying on Javascript.

Here's the snippet of code I have for cart.js:

var updateBtns = document.getElementsByClassName('update-cart')
console.log("Working");

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 is:', productId, 'Action is:', action)
        console.log('USER:', user)

    })
}

Additionally, here is the code snippet for the index.html template:

{% for product in products %}
{{ product.title }}
{{ product.price}}

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

Although print(product.id) successfully retrieves the specific product id, the button is not functioning as intended. Can you help identify what might be the issue with my code?

Answer №1

Have you initiated the action by calling it?

for (let i = 0; i < updateBtns.length; i++) {
    updateBtns[i].addEventListener('click', function(){
        let productId = this.dataset.product
        let action = this.dataset.action

        // Make sure to execute the action
        window[action](productId);

        console.log('productId:', productId, 'Action:', action)
        console.log('USER:', user)

    })
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Troubleshooting JavaScript Functions Failure Following AJAX XML Request

My current project involves developing an interactive map where users can select a year from the timeline and apply filters. This functionality is achieved through XML HttpRequest, which refreshes the SVG each time a selection is made. The SVG code for th ...

Instructions on how to insert a new row into Datatables following the successful submission of a form via AJAX请求

Could someone please provide guidance on how to insert a new row into an existing datatable after a successful AJAX request? Here is the code I am currently using: $(document).ready(()=>{ $.ajax({ url: 'http://localhost:3000/api/post/getUserDat ...

Why doesn't the let variable used in a for loop initialization extend its scope to the enclosing block?

I've always been puzzled by this question: If block scopes are generated when a let or const identifier is enclosed within curly brackets, then how come the let identifier in the initialization statement of a for loop isn't accessible in the oute ...

Modify an element in an array seamlessly

Seeking a Solution: Is there a way to ensure atomicity when checking and updating a document's child array in MongoDB? Specifically, I want to see if an entry exists, update it if it does, or add it if it doesn't, all while also adjusting a coun ...

Send JSON data using jQuery and process it in Node.js

Looking for guidance on how to send json form data from JavaScript by clicking the submit button and then receiving that json data on a Node.js server. My attempts so far have only resulted in printing '{} ' on the Node.js server terminal Below ...

What is the best way to show only a snippet of about 100 words from a post?

I have created something similar. When the reader clicks on "Read more", it should display the entire text. However, I would like to first display a certain number of words (for example 100). Is it possible to set range[:100] in {{ post.text|linebreaksbr } ...

Seeking a proficient Cloud Code specialist skilled in JavaScript, focused on managing installations and channels

My experience with Javascript is limited, but as I work on my application, I realize the necessity of incorporating it into Cloud Code. I have a Parse class called Groups where I store group data including Name, Description, Users, and Requests. Name, Des ...

When a parent document is deleted, Mongoose automatically removes any references to child documents

Greetings everyone, thank you for taking the time to read my query. I am looking to remove a child object that is referenced in a parent object. Below is the structure: const parentSchema: = new Schema({ name: String, child: { type: mongoose.Schema. ...

Leveraging Scrapy/Selenium for populating fields and conducting searches on LinkedIn's advanced search page

Discover the URL for LinkedIn's advanced search feature: In my attempt to complete fields and submit a form on the LinkedIn advanced search page using Selenium with Python, I encountered a challenge. Whenever I try typing in information for fields l ...

Clearing the Redux state in my app upon exiting the page

I've come across similar inquiries, but none of them quite match my situation. When a user clicks on one of the buttons in my app, it triggers a get request to fetch data and then displays that data on the screen. However, the issue arises when I nav ...

I am having trouble with the Array Reverse function, it's not functioning properly

Take a look at this React JS code snippet: poll() { var self = this; var url = "//" + location.hostname + "/api/v1/eve/history/historical-data/" + this.state.itemId + '/' + this.state.regionId + '/40'; $.get(url, fu ...

How to implement a for loop within a Vue.js method

Within Vuejs, I have a method that updates multiple variables based on user selection. methods: { updateChart(){ this.chart1.series[1].data = [this.$store.state.selectedcities[0].value[1]]; this.chart1.series[2].data = [this.$store.state.selecte ...

Tips for extracting parameters from a URL using Express JS in a custom manner

Recently, I set up a server using the express package and encountered an issue while trying to extract parameters from the URL in a specific format. The URL structure is as follows: (notice there's no '?' indicating parameters). I am lookin ...

Comparison between JavaScript Promise .then(onFulfilled, onRejected) and .then(onFulfilled).catch(errorFunc) in handling asynchronous operations

As I was reviewing promises, I had a question about the order in which the .then/catch calls are executed when using the code below. Are the catch calls being placed at the end of the queue stack? I already have a clear understanding of the distinction bet ...

Fetching data from database and populating dropdown menu through Struts 2 action class with the assistance of jtable

Utilizing the jtable jQuery plugin (http://jtable.org/) in my current project has been a game-changer. It allows for the creation of AJAX based CRUD tables without the need to code HTML or JavaScript. For more details, refer to this image: The jtable cod ...

centered shape-outside within a div

I'm looking to create a layout with paragraphs displayed in columns, with a middle paragraph centered within the parent div. The text of the paragraphs should wrap around the middle paragraph with some margin. Check out the reference photo Below is ...

How can I retrieve the body from a GET request using Express?

Every time I attempt to execute my code, it returns an error message indicating invalid text. app.post("/charge", (req, res) => { console.log(req.body) }) ...

Leverage the Ajax response within a Jade template

I'm currently utilizing ExpressJS with the Jade template engine. My goal is to achieve the following: Within a Jade file, I need to extract a variable that will be used in a JavaScript file. This JavaScript file will then make an Ajax request to the ...

What could be causing the ExcelJs plugin to malfunction in Internet Explorer 11?

My current setup involves Angular 9 and excelJs 4.1.1, which works perfectly in Chrome but throws an error in IE11 stating: "Invalid range in character set" in polyfills-es5.js Surprisingly, when I remove this dependency from package.json, everything func ...

Having trouble with the functionality of a simple jQuery toggle menu on mobile?

I am experiencing an issue with a simple toggle menu that utilizes jQuery's on: tap feature, but it is not functioning as expected: <nav id="mobile-nav"> <ul> <li>Item 1</li> <li>Item 2</li> ...