Populating the shopping cart with items

In the process of developing a web application, we are implementing functionality that allows users to add line items and modify the price, quantity, and description.

After some hard work, we have made progress and you can view our work here:

http://jsfiddle.net/75m7e/2067/

You can see the issue demonstrated here:

This is the JAVASCRIPT code:

function CartForm($scope) {
        $scope.searchInfo = [];
    $scope.invoice = {
        items: [{
              product_name: 'x',
              qty: 10,
              description: 'item',
              cost: 9.95
            },
            {
              product_name: 'y',
              qty: 170,
              description: 'item',
              cost: 8
            },
            {
              product_name: 'z',
              qty: 150,
              description: 'item',
              cost: 7
              }],
         selectedItem : []
    };

    $scope.addItem = function() {
        $scope.invoice.selectedItem.push({
            qty: null,
            description: null,
            cost: null,
            product: null,
            total: null
        });
    };

    $scope.removeItem = function(index) {
        $scope.invoice.selectedItem.splice(index, 1);
    };

    $scope.total = function() {
        var total = 0;
        $scope.invoice.selectedItem.forEach(function(item, index){
            total += item.total;
        })
        return total;
    };

    $scope.calculateTotal = function(selected, index){
        $scope.invoice.selectedItem[index].description = selected.description;
      $scope.invoice.selectedItem[index].qty = selected.qty;
      $scope.invoice.selectedItem[index].cost = selected.cost;
      $scope.invoice.selectedItem[index].product = selected.product;
      $scope.invoice.selectedItem[index].total = selected.qty*selected.cost;
    };
}

If you visit the provided URL, you will notice that changing the quantity or cost for one row affects other rows with the same product name. Each row should maintain unique quantity and cost information without affecting others.

I am struggling to figure out where I went wrong in my code.

Your assistance in resolving this issue would be greatly appreciated. Thank you in advance!

Answer №1

function ShoppingCart($scope) {
    $scope.cartItems = [];
    $scope.receipt = {
        items: [{
                product_name: 'apple',
                qty: 5,
                description: 'fruit',
                cost: 1.99
            },
            {
                product_name: 'banana',
                qty: 10,
                description: 'fruit',
                cost: 0.79
            },
        ],
        selectedItems: []
    };

    $scope.addItemToCart = function() {
        $scope.receipt.selectedItems.push({
            qty: null,
            description: null,
            cost: null,
            product: null,
            total: null
        });
    };

    $scope.removeItemFromCart = function(index) {
        $scope.receipt.selectedItems.splice(index, 1);
    };

    $scope.calculateFinalTotal = function() {
        var finalTotal = 0;
        $scope.receipt.selectedItems.forEach(function(item, index) {
            finalTotal += item.total;
        })
        $scope.totalCost = finalTotal;
    };

    $scope.updateItemDetails = function(selectedItem, index) {
        $scope.receipt.selectedItems[index].description = selectedItem.description;
        $scope.receipt.selectedItems[index].qty = selectedItem.qty;
        $scope.receipt.selectedItems[index].cost = selectedItem.cost;
        $scope.receipt.selectedItems[index].product = selectedItem.product;
        $scope.receipt.selectedItems[index].total = selectedItem.qty * selectedItem.cost;
        $scope.calculateFinalTotal();
    };
}

Answer №2

The conflict arises between the index of invoice.selectedItems and the selected model in $scope.selected.

For a solution, refer to the functional Fiddle provided: http://jsfiddle.net/75m7e/2069/

To address this issue, I have made an update in the code by passing the item from ng-repeat and ng-change methods using the item parameter which will then be updated with the $scope.selected model.

Answer №3

Give this a try ;)

function CartForm($scope) {
  $scope.searchInfo = [];
  $scope.total = 0;
  $scope.invoice = {
    items: [{
      product_name: 'x',
      qty: 10,
      description: 'item',
      cost: 9.95
    }, {
      product_name: 'y',
      qty: 170,
      description: 'item',
      cost: 8
    }, {
      product_name: 'z',
      qty: 150,
      description: 'item',
      cost: 7
    }],
    selectedItem: []
  };

  $scope.addItem = function() {
    $scope.invoice.selectedItem.push({
      qty: null,
      description: null,
      cost: null,
      product: null,
      total: null
    });
  };

  $scope.removeItem = function(index) {
    $scope.invoice.selectedItem.splice(index, 1);
    $scope.totalFinel();
  };

  $scope.totalFinel = function() {

    //console.log('test');

    var total = 0;
    //  alert(total);
    $scope.invoice.selectedItem.forEach(function(item, index) {
        total += item.total;
        //alert(item.total);
      })
      // return total;
    $scope.total = total;
  };

  $scope.calculateTotal = function(selected, index) {
    $scope.invoice.selectedItem[index].description = selected.description;
    $scope.invoice.selectedItem[index].qty = selected.qty;
    $scope.invoice.selectedItem[index].cost = selected.cost;
    $scope.invoice.selectedItem[index].product = selected.product;
    $scope.invoice.selectedItem[index].total = selected.qty * selected.cost;
    $scope.totalFinel();
  };
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<link href="http://d1e24pw9mnwsl8.cloudfront.net/c/bootstrap/css/bootstrap.min.css" rel="stylesheet"/>
<h2>Example of Shopping Cart</h2>
<div ng:app ng:controller="CartForm">
  <table class="table">
    <tr>
      <th>Product</th>
      <th>Description</th>
      <th>Qty</th>
      <th>Cost</th>
      <th>Total</th>
      <th></th>
    </tr>
    <tr ng:repeat="item in invoice.selectedItem">
      <td>
        <select ng-options="item as item.product_name for item in     invoice.items" ng-model="selected" ng-change="calculateTotal(selected, $index)"></select>
      </td>
      <td>
        <input type="text" ng:model="selected.description" class="input-small">
      </td>
      <td>
        <input type="number" ng:model="selected.qty" ng:required class="input-mini" ng-change="calculateTotal(selected, $index)">
      </td>
      <td>
        <input type="number" ng:model="selected.cost" ng:required class="input-mini" ng-change="calculateTotal(selected, $index)">
      </td>
      <td>{{invoice.selectedItem[$index].total | currency}}</td>
      <td>
        [<a href ng:click="removeItem($index)">X</a>]
      </td>
    </tr>
    <tr>
      <td><a href ng:click="addItem()" class="btn btn-small">add item</a></td>
      <td></td>
      <td>Total:</td>
      <td>{{total | currency}}</td>
    </tr>
  </table>
</div>

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

What is the purpose of sorting an object using the sequence defined in an array?

Have you ever wondered how the sortWeekFunction function can rearrange an object based on a predefined array order? It may seem complex at first glance, but let's break down how this code actually works. const weeksArr = ['sunday', ' ...

Enclosing sets of lists with div containers

My Objective: <ul> <li class="group4"> <ul class="group2"> <li class="first">stuff</li> <li class="last">stuff</li> </ul> <ul class="group2"> ...

Explore Python and Selenium for implementing pagination with JavaScript functionality

Having recently started using Selenium with Python 2.7, I am looking to click on certain JavaScript elements used for pagination on a website. To provide context, here is the link to the page: . Any guidance or example code would be greatly appreciated. ...

React failing to detect updated state from input fields during initial rendering

Hey there, fellow developers! I'm currently working on a simple client in React to test out some functionalities of my API. While my Node.js knowledge is extensive, my understanding of React, states, and hooks is still a work in progress. The Issue: ...

CSS Toggle Navigation for Responsive Screen Re-Size in Both Horizontal and Vertical Orientations

I'm currently working on making a navigation menu responsive. Take a look at my progress so far here: https://jsfiddle.net/a16qwd20/4/ Unfortunately, I am facing an issue where the Javascript doesn't seem to be functioning properly in JS Fiddle, ...

When html5Mode is activated, ui-router fails to direct to $urlRouterProvider.otherwise

Let me simplify this for you. Here's the reference route file: angular .module("app") .config(function($stateProvider,$locationProvider,$urlRouterProvider){ $urlRouterProvider.otherwise("dashboard"); ...

Update the row striping pattern once an element has been removed

I've been working on creating a todo-list and implemented row striping. Everything was going smoothly until I realized that when I delete a task, the row striping does not update as intended. Instead of changing to white, white, beige after a deletion ...

The issue with text color not displaying properly within a Material-UI Theme

While designing a color theme using Material-UI, I specified the contrast text as white (#fff). Surprisingly, it seems to work for buttons with the primary color but not for those with the secondary color. I attempted overrides following the suggestions p ...

Recover information following file uploads to gridfs using angular-file-upload

Uploading files from my controller to the server involves using gridfs to write them. Once the writestream is closed, I can retrieve the file._id and log it to the terminal. However, I am facing a challenge of setting a variable in my angular controller t ...

What is the best way to organize products based on the proximity of users using MongoDB's Geospatial Queries

I'm currently working on a web application that connects users with neighbors to buy and sell products. The app is built using node.js, JavaScript, mongodb, and mongoose. My main issue lies in sorting the products. I want to display products from nea ...

Steer clear of using the hashtag in a URL when using angular-ui-router

I am encountering an issue with my angular application that utilizes angular-ui-router for routing. app.config(function($stateProvider, $urlRouterProvider) { $stateProvider .state('home', { url: "/home", templateUrl: "t ...

The ngResource module failed to instantiate within the angular/browserify environment

Recently, I decided to test out browserify in conjunction with Angular. After adding ng-resource to my project using the following command: npm install --save ng-resource I attempted to load it into my code like this: require('angular'); requi ...

There is a necessary pause needed between carrying out two statements

I am currently working with extjs 4.2 and I have encountered a situation where I am loading the store object in the following manner: var userDetailStore = Ext.create('Ext.data.Store', { model: 'Person.DetailsModel', autoLoad: ...

Capture various data points in an array with each click

I am currently working on a menu of buttons where users can select multiple options at the same time. My goal is to record all selected buttons in one array instead of individual arrays for each button. The end result I hope to achieve is an array like t ...

Identifying the Occurrence of a Partial Insertion in Rails through JavaScript/jQuery

Is there a way to determine if a partial is currently visible using JavaScript? Let's simplify this with some pseudo-code to explain my question - In this scenario, in my controller: def index if (request.xhr?)//coming from pagination ajax requ ...

The JavaScript API for YouTube - when the state changes

I am facing a challenge while trying to embed a YouTube video onto one of our customer's websites. The requirement is for the video to display an image once it has finished playing. My initial approach was to remove the containing div so that an under ...

Fullpage.js paired with a carousel

Is there a reason why two carousels are not aligning side by side when using fullpage.js? It seems to work perfectly fine without fullpage.js! In Fullpage.js, even after separating the columns for the two carousels, they end up overlapping each other. How ...

Is there a way to remove a particular map from Firestore?

In my Google Firebase setup, I have uniquely named each Map to serve as the index for every document. Using Vuejs (Javascript), I have structured it as follows: eQFelbD432T (Collection Name- user.uid) SKILLS (Document Name) ProjectManangement (Map Na ...

Encountering difficulty retrieving the value of a hidden input with jQuery's find method

When a user clicks on the delete icon, I want to retrieve the value of the hidden input inside the "delete" class. However, I am getting an undefined result. Can someone please guide me on where I might be going wrong? <table class="items-list"> ...

What is the correct way to display the date in a React application?

I am working on a project that involves integrating solidity contracts into a web portal. In one of the contracts, I have stored dates as uint values like this: 1539491531. However, when I display these dates on the web page, they appear different from wh ...