The "add to cart" button is unresponsive

My issue is that the add to cart button on my website is not responding properly. I have implemented JavaScript on the add to cart button, where I have assigned an attribute called data-product with a value of {{product.id}}.

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('productId:', productId, 'action:', action)

  })
}
<div class="card-body">
  <h5 class="card-title fw-bold text-uppercase">{{product.name}}</h5>
  <p class="card-text">
    <h4 style="font-size: 1rem; padding: 0.3rem;
            opacity: 0.8;">$ {{product.price}} </h4>
  </p>
  <button data-product={{product.id}} data-action="add" class="btn btn-outline-secondary add-btn update-cart">ADD TO CART</button>
</div>
</div>

Despite clicking on the Add to Cart button multiple times, nothing is being displayed in the console.

Answer №1

Try using querySelectorAll instead of getElementsByClassName. According to @tacoshy, getElementsByClassName returns an HTML Collection object, not an array. Additionally, the length property will count the elements in an array, not an object.

const updateBtns = document.querySelectorAll('.update-cart')

updateBtns.forEach((updateBtn) => {
    updateBtn.addEventListener('click', (event) => {
        var productId = updateBtn.dataset.product
        var action = updateBtn.dataset.action

        console.log('productId:', productId, 'action:', action)
    })
})

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

The output of JSON.stringify() when given a single value as input

The JSON.stringify() function is designed to convert a JavaScript value into JSON format. console.log(JSON.stringify('a')); //output: "a" console.log(JSON.stringify(1)); //output: 1 console.log(JSON.stringify(true)); //output: true However, tec ...

Tips for obscuring URLs in AngularJS code without relying on base 64 encoding or Gulp obfuscation techniques

I'm looking for a way to obfuscate specific URLs in my AngularJS code without using base 64 encoding. Is there a method to only obfuscate URLs? var app_data = { 'APP_CONFIG': { 'USER_URL': 'http://127.1.1.0:8000/ ...

Customizing Styles in Material UI with React

I am facing an issue with customizing the styles in my Material UI theme in React. Specifically, I am trying to modify the border of the columnsContainer but it doesn't seem to work, only the root style is having an effect. Take a look at this Codesa ...

Dealing with a Nodejs/Express and Angular project - Handling the 404 error

Recently, I decided to dive into learning the MEAN stack and thought it would be a great idea to test my skills by building an application. My goal was simple: display a static variable ('hello') using Angular in the HTML. However, I ran into an ...

Implementing a time to live feature in socket.io can be accomplished by setting a

After extensive searching online, I haven't been able to find any resources on how to implement the 'time-to-live' function using Socket.io. In my project, I am utilizing Node.js with express. The functionality of the mentioned time-to-live ...

Vue Js does not include images in the dist directory when the build process is completed

In my VueJs 3 project, I am working with a list of PNG images stored in the src/assets/pngs/ directory. Within my Vue component, I use a For loop to dynamically create the list by setting the image name as the source for the img tag. This implementation wo ...

Why do I keep receiving the error message "Cannot set property of undefined"?

In the midst of a small project that involves utilizing nuxt, js, and axios, I encountered an issue when attempting to assign the response data to my formFields object. Despite having declared formFields within the data section, I kept receiving an error m ...

Redux state not reflecting changes until second click

My redux store has a simple boolean setup to track whether a sidebar is expanded or not. However, I'm encountering an issue where, even though the default value is false, clicking the toggle button outputs false first. Ideally, if it's initially ...

I'm having trouble importing sqlite3 and knex-js into my Electron React application

Whenever I try to import sqlite3 to test my database connection, I encounter an error. Upon inspecting the development tools, I came across the following error message: Uncaught ReferenceError: require is not defined at Object.path (external "path ...

The QR code disappears from the screen once the button is no longer pressed

After following an online tutorial on creating a QR code generator, the code works fine and I am able to display the image. However, I'm facing an issue where the image disappears from the screen once the button is released. Here is the code snippet: ...

What is the reason behind this HTML/CSS/jQuery code functioning exclusively in CodePen?

I have encountered an issue where this code functions properly in JSFiddle, but not when run locally in Chrome or Firefox. I suspect there may be an error in how the CSS or JavaScript files are being linked. In the Firefox console, I am receiving an error ...

What is the best way to eliminate YouTube branding from a video embedded in a website?

I am currently utilizing an <iframe width="550" height="314" src="https://www.youtube.com/embed/vidid?modestbranding=1&amp;rel=0&amp;showinfo=0" frameborder="0" allowfullscreen></iframe> This setup removes the "YouTube" logo from the ...

javascript variable pointing to an unknown object

Below is the essential code snippet to consider: JS function ToggleRow(objTwistie, objRow) { if (objRow.style.display == "none") { objRow.style.display = ""; objTwistie.src = "../Images/SectionDown.gif"; } else { objRow.style.display = "n ...

The ReactJS component is unable to resolve the specified domain name

Whenever I utilize a component like const React = require('react'); const dns = require('dns'); class DnsResolver extends React.Component { componentDidMount() { dns.resolve('https://www.google.com', (err, addres ...

The radio button element could not be located using the attribute "checked="Checked""

While working with Geb, I encountered an issue using the code div.find("input","checked":contains("checked")). This is the snippet of code I attempted to use in order to locate the checked radio button on a webpage. However, I received an error when using ...

Is it possible to pass an HTML element's id attribute to a function in JavaScript?

In the following code snippet, I am looking to send the id=content to the function mr and then display the result in the passed id=result. While this functionality is currently limited to this HTML file, I aim to extend it to other HTML pages by adding the ...

Preserve proportions while resizing the browser window

I needed my code to ensure that the images keep their aspect ratio regardless of the screen size or if the user resizes their browser instead of viewing it full screen. I have some code in place, but I'm unsure how to maintain the current effects of ...

NodeJS reference copying problem

After encountering an issue where changes to the original object were being reflected in a copy due to JavaScript referencing, I followed recommendations and updated my code as follows: const originalData = {...docid[0][0].Record} // or const originalData ...

Transmitting the User's Geographic Location and IP Address Securely in a Hidden Input Field

I'm looking to enhance my HTML form by retrieving the user's IP address and country when they submit the form. How can I achieve this in a way that hides the information from the user? Are there any specific elements or code additions I need to ...

Error: Document's _id field cannot be modified

I am new to both MongoDB and Backbone, and I find it challenging to grasp the concepts. My main issue revolves around manipulating attributes in Backbone.Model to efficiently use only the necessary data in Views. Specifically, I have a model: window.User ...