How do I adjust the amount of a product in my Django ecommerce store?

There seems to be an issue where the quantity is only being changed in the first product, even if I click on the arrow of the second product. The changes are reflected in the quantity of the first product instead. cart.js

var changeQ = document.getElementsByClassName('increase')


for (i = 0; i < changeQ.length; i++) {
    changeQ[i].addEventListener('click', function(){
        var productId = this.dataset.product
        var action = this.dataset.action
        console.log('productId:', productId, 'Action:', action)
        
        
        if (action == 'plus'){
            Increase(productId, action)
        }
        else if(action=='minus'){
            Decrease(productId, action)
        }
    })
}

function Increase(productId,action){
    console.log('Increase')
    var quantity = Number(document.getElementById("quantity").value);
    quantity = quantity+1;
    document.getElementById("quantity").value = quantity;
    console.log(quantity);
}

function Decrease(productId,action){
    var quantity = Number(document.getElementById("quantity").value);
    console.log('Decrease')
    quantity = quantity-1;
    document.getElementById("quantity").value=quantity;

}

template

<div class="counter">
    <div class="arrow-up increase" id="arrow-up" data-product="{{item.product.id}}" data-action="plus" ><i class="fa fa-arrow-up"></i></div>
    <div class="quantity"><input type="number" id="quantity" value="1"></div>
    <div class="arrow-down increase" id="arrow-down" data-product="{{item.product.id}}" data-action="minus"><i class="fa fa-arrow-down"></i></div>
  
  </div>

These code snippets are used in a Django project. What steps can I take to address this issue and ensure that the quantity changes are applied to the correct products? Any assistance would be greatly appreciated!

Answer №1

If you've utilized the document.getElementById() method in both the Increase and Decrease functions, it will only target the first element with the ID of 'quantity'. This explains why you can only manipulate the quantity for the first product.

To resolve this issue, I suggest using a unique identifier to differentiate between the input tags that have an ID of 'quantity'. One solution could be adding

data-product="{{ item.product.id }}"
to the input tag, as you are already passing the product ID as productId to both functions.

Below is how your template should be structured:

<div class="counter">
    <div class="arrow-up increase" id="arrow-up" data-product="{{item.product.id}}" data-action="plus" ><i class="fa fa-arrow-up"></i></div>
    <div class="quantity"><input type="number" id="quantity" value="1" data-product="{{item.product.id}}"></div>
    <div class="arrow-down increase" id="arrow-down" data-product="{{item.product.id}}" data-action="minus"><i class="fa fa-arrow-down"></i></div>
</div>

You'll also need to update the Increase and Decrease functions as shown below:

function Increase(productId,action){
    console.log('Increase')
    var quantity = Number(document.querySelector(`input[data-product=${productId}]`).value);
    quantity = quantity+1;
    document.querySelector(`input[data-product=${productId}]`).value = quantity;
    console.log(quantity);
}

function Decrease(productId,action){
    var quantity = Number(document.querySelector(`input[data-product=${productId}]`).value);
    console.log('Decrease')
    quantity = quantity-1;
    document.querySelector(`input[data-product=${productId}]`).value=quantity;
}
  • document.querySelector() enables us to select elements using CSS selectors, which we use here to target input tags based on the value of the data-product attribute matching productId.
  • We utilize ${} for string interpolation, allowing us to insert the value of productId into the selector string.

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

Guide on fetching and adding information with a single web API call in AngularJS

In this code snippet, I am utilizing the "$http.get" request to fetch data from a Web API in Angular.js. The API URL includes a parameter called "pageNo=" which requires a digit to be added at the end in order to retrieve data for a specific page number. ...

The error message from Django regarding password change did not produce an HttpResponse object as expected; instead, it returned None

I have created a form to change passwords using the following code. forms.py class PasswordChangeForm(forms.Form): password = forms.CharField(max_length=32,required=True,widget=forms.PasswordInput) repassword = forms.CharField(max_length=32,requi ...

What steps can be taken to restrict a user from inputting a value if the preceding field is

In the form I'm working on, there are City and Building fields. I need to ensure that before the user submits the form, the system checks if a building already exists in the selected city. While building numbers can be the same, they should not belong ...

Difficulty arises when switching between the coordinates of a wavefront (.obj) in three.js

Currently, I am dealing with a slider in my HTML code that has values ranging from 1 to 2. When the slider value is set to 1, I intend to adjust the coordinates of my wavefront as described by arrayMin. Conversely, when the slider is at 2, I wish for the w ...

Updating a form section using Ajax and displaying the updated results on the current page

In my attempt to achieve a goal, I came across this helpful resource: Here is a condensed version of my model: public class Iro : EntityBase { public int ReportYear { get; set; } public Guid DcmDataCallId { get; set; } public ...

Tips for loading Images from a different URL in Three.js

Hello all, I'm completely new to threejs and currently working on loading a texture to a cylinder from a different web directory. If anyone can offer some guidance on what might be incorrect in the following code snippet, that would be really helpful: ...

I'm attempting to determine the total cost of the product prior to the application of any discounts

Is there a way to calculate the original price of a product before applying a discount in Django using the formula: price / (1 - discount%)? Example: <span class="old-price">{{......}} L.E</span> class Product(models.Model): se ...

Struggling with serving static content on NodeJS using Express.js

I set up a basic NodeJS and Express server on my development machine running Windows 10. var express = require('express'); var app = express(); app.use(express.static('app')); app.use('/bower_components', express.static(&apo ...

When you click on the column header to sort, the corresponding column row changes color in JavaScript

https://i.sstatic.net/4ELuv.jpg When a user clicks on a column to sort, the color of the column changes or highlights the row. In my tablesorter with ascending and descending sorting capabilities, I want the sorted column to change colors for better visib ...

What is the most effective way to transfer content from the clipboard?

I need to transfer content from one div to another by copy/pasting When I click the paste button in the example below, the expected result in the target div is - <p>lorem ipsum</p> but unfortunately, nothing happens $('.btncopy&apos ...

Make sure to save your data prior to using req.session.destroy() in Express

Before destroying the session in the logout route, I need to save the session value "image location" into the database. Here is the solution I have implemented: app.get('/logout',function(req,res){ Person.update({ username: req.session.use ...

Is it possible to automatically redirect to another page once two text inputs have been filled without the use of a button?

Looking to create a basic static demonstration resembling Uber, but struggling to figure out how to trigger a redirect or any kind of action once both input elements have been filled. I plan to include two input fields similar to this example and aim to a ...

jQuery functions are failing to execute when called within the .ready() function

I am new to using jQuery and I am facing an issue with setting up my click events. The strange thing is that when I use alert('');, it shows that the menu.js file is referenced correctly. However, when I try to use alert within the .ready() funct ...

Display Edit Button Only for Post Owners in Django

I'm currently working on a Django project that involves posts and the functionality to edit them. The main index page serves as a news feed displaying all the posts. However, I'm facing an issue where anyone can edit any post, but I want to restr ...

Troubleshooting the failure of the addEventListener mouseEvent in an Angular environment

Recently, I've been encountering an issue with adding addEventListener to dynamically created HTML canvas elements. Everything was working fine before, but now none of the events seem to be triggered. Below is the code snippet I am currently using: t ...

Troubleshooting problem with MongoDB queries within a for loop

I have an array of user emails obtained from the post data. My goal is to find the _id associated with each email. Here's the for loop I attempted: var studentIds = []; for (var i = studentEmails.length - 1; i >= 0; i--) { var email = studentEm ...

Is there a way to make sure that my submit button aligns perfectly with the text beneath it

I am new to coding and I need help aligning my submit button with the text "You can contact Armando through his freelance portfolio on Upwork by clicking...". Can anyone assist me with this? .topnav { background-color: #333; overflow: hidden; } .to ...

Encountering a 404 Error in React Native when using Axios - The request was unsuccessful with status code 404

I am facing an issue while trying to retrieve data from an API in Brazil. The API is returning the following error: Object { "_link": "/v1/campeonatos/2/fases/56", "decisivo": false, "eliminatorio": true, "fase_id": 56, "ida_e_volta": false, " ...

If a certain condition is met within an ng-repeat loop on a particular variable

When obtaining information in angularjs from an SQL query, it may appear as follows: {"orders":[ { "orderId":"1674","itemId":"468","SubTotal":"40.00","Total":"48.98","Status":"Printed","Title":"Mangled : Large","Quantity":"1","dateCreated":"2009-06-03 ...

Ways to modify object in Django using links?

I'm encountering an issue with Django. I am trying to modify a specific field in a model using a hyperlink, but I am unsure of how to proceed. I attempted the code below, but it does not seem to have any effect. views.py: def updatePlayer(request, p ...