How to remove an item from the shopping cart and use a discount code with JavaScript

I need help with removing an item from the cart without deleting the entire cart, and also adjusting the price if the customer has a coupon or exceeds a certain quantity. I am working on this using JavaScript before implementing it in Django. Here is the HTML code along with some JavaScript, please let me know if you have any suggestions.

HTML

<div data-name="name" data-price="250" data-id="2">
    <img src="x.jpg" alt="" />
    <h3>name</h3>
    <input type="number" class="count" value="1" />
    <button class="tiny">Add to cart</button>
</div>

<script type="text/template" id="cartT">
    <% _.each(items, function (item) { %> 
        <div class="panel"> 
            <h3> <%= item.name %> </h3>  
            <span class="label">
                <%= item.count %> piece
                <% if(item.count > 1) {%>
                    s
                <% } %> for <%= item.total %>$</span> 
            </div>
    <% }); %>
</script>

JavaScript

addItem: function (item) {
    if (this.containsItem(item.id) === false) {
        this.items.push({
            id: item.id,
            name: item.name,
            price: item.price,
            count: item.count,
            total: item.price * item.count
        });
        storage.saveCart(this.items);
    } else {
        this.updateItem(item);
    }
    this.total += item.price * item.count;
    this.count += item.count;
    helpers.updateView();
},
containsItem: function (id) {
    if (this.items === undefined) {
        return false;
    }
    for (var i = 0; i < this.items.length; i++) {
        var _item = this.items[i];
        if (id == _item.id) {
            return true;
        }
    }
    return false;
},
updateItem: function (object) {
    for (var i = 0; i < this.items.length; i++) {
        var _item = this.items[i];
        if (object.id === _item.id) {
            _item.count = parseInt(object.count) + parseInt(_item.count);
            _item.total = parseInt(object.total) + parseInt(_item.total);
            this.items[i] = _item;
            storage.saveCart(this.items);
        }
    }
}

Answer №1

If you want to delete a specific item based on its ID, you can utilize the filter function in JavaScript. This method allows you to remove only the item with the matching ID.

removeItem(id) {
   this.items = this.items.filter(item => item.id !== id);
}

When applying a coupon, consider making an HTTPS call to verify its validity and value before adding a discount to the cart. Unless all coupons are stored locally, this is a recommended approach.

In your code, optimizing the containsItem function by using the some method can improve efficiency as it automatically checks for the item's existence in the array.

containsItem: function (id) {
   return this.items?.some(item => item.id === id);
}

//PS: Use ?. to avoid undefined errors when checking if the variable exists. This is known as [Optional Chaining][2]

For updating items, consider utilizing the find function to retrieve the specific element needing modification.

updateItem: function (object) {
   const itemToUpdate = this.items.find(item => item.id === object.id);
   if(itemToUpdate) {
      itemToUpdate.count = parseInt(object.count) + parseInt(itemToUpdate.count);
      itemToUpdate.total = parseInt(object.total) +parseInt(itemToUpdate.total);
      storage.saveCart(this.items);
  }
}

Furthermore, there is no need to reassign the array after updating elements, as changes made to the referenced object will reflect directly in the source.

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

Error in node - Invalid URI received during npm-request operations

var request = require('request'); var options = { url: 'https://connect1on1.com/api/web/index.php/v1/message/save-message', method:'POST', body:JSON.stringify({"id": data.user_id, "message": data.me ...

Google Book API is a tool provided by Google that

I am trying to loop through the items array provided by the Google Books API and display the result within a div, but I'm having trouble doing so. Here is my current code: <body> <div class="main-body"> <form id="form"> ...

Adding information to a MySQL database using PHP/AJAX, triggering the success function only once the data has been successfully inserted (Callback)

I've been struggling to create a basic website, and some of the information provided here is confusing and irrelevant to my specific situation. My website features a form with three input fields, a button, and a list. When the submit button is clicke ...

Unable to pass parameters using ViewBag in jQuery within a partial view

Currently, I am in the process of building an MVC3 application with razor syntax. My focus right now is on developing the partial class that will be responsible for handling comments. This is a snippet of my code: <script src="../../Scripts/jquery.js" ...

Dynamic navigation experiencing erratic behavior when using display flex

I attempted to enhance my previous projects by converting them into flexbox. However, I ran into an issue where the ul element was displaying as a block. To fix this, I used JavaScript to change it to display flex. Here is the fiddle: // JavaScript co ...

Converting a multidimensional array into a JSON string using the json_encode

I've been experimenting with json_encode techniques for a while now, but I'm still struggling to achieve my desired outcome. I have developed a PHP function that reads data from a CSV file and stores it in a multidimensional array (pretty confid ...

Ensuring a correct dismount of a React component

Apologies for the lack of specificity in the title of this inquiry. Upon executing the code snippet below, I encountered the ensuing warning: Warning: setState(...): Can only update a mounted or mounting component. This typically indicates that you call ...

Can anyone provide guidance on how to simulate a click on a JavaScript action for an iPhone?

I am attempting to trigger a click on a "javascript:void(0)" link so that I can retrieve HTML data within the script. Can someone advise me on how to achieve this without using illegal APIs like UITouchEvent, as I only work with NSUrl? Thank you in advan ...

What is the process for transmitting instructions to receipt printers from a Django application?

After completing a simple POS application, I need to figure out how to send a command to the receipt printer to print the receipt. I am stuck as I have no code to address this issue and don't know where to begin. I have a few questions: 1) I've ...

Incomplete data was retrieved from the localStorage

I am currently in the process of developing a mobile application using Phonegap version 1.4.1. I have encountered an issue on iOS (running on version 5.1) where the app fails to load all data from localStorage. Upon first use of the app, I set a flag in l ...

What is the process for unbinding an externally created event in a directive?

Is there a way to prohibit copy-pasting in the Textangular module without modifying its code? While examining the code, I discovered an event binding for the "paste" action. Could the paste event be unbound from outside the module? Perhaps upon loading th ...

Typescript's static classes are a powerful and convenient way to

Does anyone know how to implement a static class in TypeScript and Node.js? I am interested in creating a static class to store all constants and strings in one place. Any suggestions on the best approach to achieve this? ...

Loading JS and CSS files in relation to the website root directory

When it comes to including CSS/JS files, what are the best practices for defining the file URI? Some people prefer to include files relative to the website root by specifying the full URI: <link rel="stylesheet" href="/my/path/to/css/main.css"> Thi ...

Attempting to make a slightly bigger than usual AXIOS.post request to a .NET Web API

When attempting to perform an AXIOS.post in a Vue.JS application, the process fails when exceeding about 1500 characters. Instead of reaching the Web API, it goes directly to the error area. Typically, this function calls a .Net Web API that generates a MS ...

Is there a way for me to generate a preview thumbnail for my video?

Looking to add a preview effect to video thumbnails when users hover over them, displaying a series of frames from the video. Are there any jQuery plugins or tutorials available for creating this effect? ...

What is the procedure for updating a user's password using mongoose?

I have a new feature on my website that allows users to reset their password if they forget it. Here are the packages I am using: Express Js (framework) passport-local--mongoose, passport-local, passport, I'm implementing the passport method . ...

Tips for extracting the most deeply nested object in a JSON file using JavaScript

Is it possible to access the innermost object without knowing the path names? Consider this JSON example: const data = { first: { second: { third: {innerObject} } } ...

Error 1054 in Django Models: "Field list column is not recognized"

I am facing a problem with an error message stating "Unknown column in field list". Any assistance in resolving this issue would be greatly appreciated. OperationalError at /admin/login/person/ (1054, "Unknown column 'login_person.status_info' i ...

What is the best method for storing dynamic values and attribute labels in a state within a React.js application?

I am currently working with react js. On my single product page, I have an array of objects called attributes that I need to display in the user interface. Here is a preview of how it looks: https://i.sstatic.net/GttrD.png My goal is to retrieve and stor ...

Triggering JavaScript Function When Scrolling in Overflowed DIV

After using jQuery and searching for various ways to make this script work, I finally found a solution that works for my index.html file. <div style="overflow-y:scroll; height:300px"> <div style="background-color:black; height:500px"> </div ...