Innovative form creation using Vue.js

My interactive form allows users to input an item, quantity, and cost per item like this:

<form @submit.prevent="submit">

  <div class="form-group" v-for="(input,k) in inputs" :key="k">

    <input type="text" class="form-control" v-model="input.item">
    <input type="text" class="form-control" v-model="input.quantity">
    <input type="text" class="form-control" v-model="input.cost">
    <span>
      <i class="fas fa-minus-circle" @click="remove(k)" v-show="k || ( !k && inputs.length > 1)">Remove</i>
      <i class="fas fa-plus-circle" @click="add(k)" v-show="k == inputs.length-1">Add fields</i>
    </span>
  </div>
  <button>Submit</button>

</form>

I'm looking to calculate the total cost of all the items added. I attempted it with:

export default {
  methods: {
      totalCost: function () {
          for (let i = 0; i < this.inputs.length; i++) {
              return this.inputs[i].cost*this.inputs[i].quantity
          }
      }
  }
}

However, this only provides the total cost of the first item. How can I get the total cost of all user-input items?

Answer №1

The return statement in the for-loop causes the function to stop executing after calculating the cost of the first item.

To fix this issue, you can eliminate the return and instead keep track of the total sum by using a local variable:

let total = 0
for (let i = 0; i < this.inputs.length; i++) {
  total += this.inputs[i].cost * this.inputs[i].quantity
}
return total

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

Embedding images using a blob or base64 format does not function properly on iOS devices

I'm facing an issue with setting the src of an img tag to display an image. The code snippet below works fine on android, mac, and windows, but it is not functioning correctly on iOS: let base64Image = pageModel.image; this.$currentPageImage.src = `da ...

Incomplete data retrieval issue encountered during .ajax call

I am having trouble retrieving all 4 key|value pairs from a page that displays an object as text in the body and pre tag. It seems to be missing one pair - any ideas why? Just a heads up, I've tweaked some of the URLs and data in the JSON output for ...

Replacing parts in Vue when clicking on an element

I am currently working on a website with a storytelling concept. The idea is that when a user clicks on a certain element, a new layout will be shown - either a full-screen video or an image. After clicking the "next" button, a different content should be ...

Ways to resolve a 500 internal error

I have created an online test system for students, but I am facing an issue with passing answers in JSON format. Whenever I attempt to do so, I encounter a 500 internal error and I am unable to identify the root cause. Even after removing lengthy JSON dat ...

Guide to dynamically setting SCSS $variables in JavaScript after retrieving them from local storage in a React application

In my current situation, I am retrieving color combinations in hash values from the database through an API call and then saving them in localStorage for future use. However, I am facing a challenge when trying to access this data from localStorage and uti ...

Using Jquery to add a list after parsing JSON data stored in localStorage

I've been stuck on this issue for quite some time now. The problem I'm facing involves checking the localStorage to see if there's a cached JSON string available. If there is, I load it and convert it back into a JSON object. If not, I make ...

Persisted state in Vuex fails to retain data after the page is refreshed

I recently added persisted state to my Vue application using the command npm install --save vuex-persistedstate. After that, I configured my Vuex store.js file in the following way: import Vue from 'vue' import Vuex from 'vuex' import ...

Tips on displaying tooltips on multiple graphs in Highcharts using Vue 3

I am currently utilizing vue3-highcharts in conjunction with Highcharts. My goal is to replicate a similar functionality as shown in this example: https://codepen.io/lzl124631x/pen/KLEdby?editors=1010. However, I am unsure about the correct syntax for impl ...

ID could not be retrieved from the checkbox

I am facing an issue with my HTML checkboxes. The ids are generated from an angular ng-repeat, but when I try to collect the id for use, it always returns as undefined. $("input:checkbox.time-check-input").each(function () { var ruleUnformatted = ""; ...

Is there a way to assign innerHTML values to table cells using PHP?

I'm currently building a website that relies on a database to store information. I have created an array to hold the values retrieved from the database, and now I need to populate a table with these values. Each cell in the table has a numerical ID ra ...

What is preventing my data from generating a table in BootsrapVue?

My Vue script looks like this: export default { name: 'app', components: { }, data(){ return{ image: null, isLoaded: false, items: [] } }, created(){ this.divtest() this.getTimeTable() }, methods ...

Developing view logics in Angular using ng-grid/ui-grid

Exploring the possibilities of creating a grid with advanced features such as filtering, resizing, scrolling, fixed headers, row formatting, and cell formatting using AngularJS. After reviewing various grids documentation, I have come across the following ...

Accessing JSON data from a URL for use within a specific context

I am currently utilizing the request module within Express to fetch a JSON file from a specified link. var url = 'https://api.github.com/users/google/repos'; request.get({ url: url, json: true, headers: {'User-Agent': &apo ...

What does the error message "TypeError: Bad argument TypeError" in Node's Child Process Spawn mean?

Every time I execute the code below using node: var command = "/home/myScript.sh"; fs.exists(command, function(exists){ if(exists) { var childProcess = spawn(command, []); //this is line 602 } }); I encounter this error: [critical e ...

Tips on invoking a method from a JavaScript object within an AJAX request

Considering the following code snippet: var submit = { send:function (form_id) { var url = $(form_id).attr("action"); $.ajax({ type: "POST", url: url, data: $(form_id).serialize(), dataType: 'json', succes ...

Learn how to transform a raw readme file into an HTML formatted document using AngularJS, after retrieving it from GitHub

Can someone help me figure out how to format each line of the README.MD raw file into an HTML document using the controller below? angular.module('ExampleApp', []) .controller('ExampleController', function($scope, Slim,$sce) { ...

The route handler for app.get('/') in Express is not returning the input data as expected

I have multiple routes set up, and they are all functioning properly except for the app.get('/') route. When I navigate to 'localhost:3000/', nothing is being displayed in the backend console or on the frontend. The Home component is su ...

What are the recommended callbacks for initiating ajax calls and managing files/chunks during dropzone chunk uploading?

I am currently working on implementing chunk uploading using dropzone js and php. My main concern is regarding the placement of ajax calls in this process. When dealing with single file uploads, specifying the URL parameter is sufficient. However, when ...

Duplicate values of React object properties when using .push method within a loop

In my code, I've implemented a function called handleCreate that is responsible for taking user data and inserting it into a database. Within the loop of aliasArr.forEach(), I am sending new user instances to my database for each element in the alias ...

Loading background images in CSS before Nivo slider starts causing a problem

I've been struggling with preloading the background image of my wrapper before the nivo-slider slideshow loads. Despite it being just a fraction of a second delay, my client is quite particular about it -_- After attempting various jQuery and CSS tec ...