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

Is there a method to programmatically identify enterprise mode in IE11?

Is it possible to detect Internet Explorer 11 Enterprise mode programmatically? This would involve detecting at the server side using C# or JavaScript/jQuery. The discussion on the following thread has not reached a conclusive answer: IE 11 - Is there a ...

What could be the reason behind the disruption in this JavaScript associative array?

I'm facing an issue with my associative array, which I have confirmed through console.log to be initially: this.RegionsChecked = {"US":true,"APAC":true,"Canada":true,"France":true,"Germany":true,"India":true,"Japan":true,"LATAM":true,"MEA":true,"UK": ...

Execute command problem

Explaining this code may be a bit tricky, but I'll do my best. Below is the code snippet for executing a slash command. client.on('interactionCreate', async interaction => { if (!interaction.isCommand()) return; const command = c ...

Stopping the webdriver in Node.js gracefully without crashing it can be achieved through a

Can the selenium webdriver be halted without terminating node? I've encountered a problem attempting to create an API tool that conducts web automation upon receiving a get request. Essentially, I am executing the selenium webdriver on a get request ...

A step-by-step guide on extracting nested ASP.NET DataGrid values with JavaScript

Looking to retrieve data from a nested data grid on an aspx page using JavaScript. Check out the following code snippet: <tr> <td colspan="2" align="center"> <asp:DataGrid ID="sampleData" AutoGenerateColumns="false" runat="serv ...

JavaScript code to convert a query into an array

Is there a way to search through a JavaScript array to find all names that start with the letter A? If so, how can I display all of the information associated with those names? Name":"Albert","age":"14" Name":"Alison","age":"14" Here is my JSON array: ...

Identifying the method of navigation using PerformanceNavigationTiming

Previously, I was able to determine if a user had arrived on the page by clicking the back button in the previous page using window.performance.navigation.type like this: if (window.performance.navigation.type === 2) { window.location.reload() } Howe ...

Guide on attaching an event to every dynamically created element in JavaScript

I'm currently generating 'li' elements dynamically using a loop and running into issues when it comes to assigning events to each generated element. My goal is to assign an onclick event to every li element that is created. Check out the co ...

Utilizing JavaScript to display numerous variables within a text box

After creating an HTML form, I encountered an issue where only one selected item was displayed in the text field. Can anyone help me solve this problem so that multiple names can be printed in the textfield? function myFun(extras) { document.get ...

Using HTML input checkboxes in conjunction with a JavaScript function

After creating a basic payment form using HTML/CSS/JS, I wanted to implement checks on user inputs using HTML patterns. In addition, I aimed to display a pop-up alert using JS to confirm the form submission only after all necessary inputs are correctly fil ...

Tips for detecting the existence of a different class within a div/ul through jquery or javascript?

This is how I have my unordered list, or "ul" element, styled. As you can observe, there are two classes defined for the ul <ul class="nav-second-level collapse"> </ul> There might be an additional class added to the same ul like so: <u ...

What is preventing this composable from being reactive?

In my application, I have implemented this composable: // src/composition-api/usePermissions.js import { ref, readonly } from 'vue' import { fetchData } from 'src/utils/functions/APIFunctions' export function usePermissions() { const ...

Customize the CSS for the column containers in Material-UI's DataGrid with the

I am facing a challenge in trying to override the CSS property position on the .MuiDataGrid-columnsContainer. Upon reviewing the information available on https://material-ui.com/api/data-grid/#css, it seems that there is a rule defined for root but not spe ...

react component fails to rerender upon state change

I am struggling with a React functional component that includes a file input. Despite selecting a file, the text in the h1 tag does not change from choose file to test. The handleChange function is triggered successfully. A console.log statement confirm ...

What benefits does NewRelic offer?

We are looking for a way to monitor events within our application and send the data to a monitoring server such as NewRelic. Our goal is to set up alerts based on this custom data. For instance, we would like to receive an alert if an event does not occur ...

JavaScript - All values stored from the for loop are registering as undefined

Recently delving into the realm of JavaScript programming, I find myself faced with a new challenge. While not my first language, this is one of my initial ventures with it. My current project involves creating a chess program utilizing the HTML5 canvas fe ...

After using res.redirect(`/relative/url`), I encountered a PATCH 404 Not Found response. Any suggestions on resolving this issue?

Issue: I have encountered a problem while trying to update a document saved on MongoDB. I used the following code snippet for updating the document: Blog.findByIdAndUpdate(req.body.id, { 'status': req.body.status }). The updating part works perfe ...

What is the best way to halt the current event handler thread's execution when another event is triggered that calls the same handler at

One of the functions in my code filters and sorts contents of a select dropdown based on input text entered by the user. The function filterSort() is triggered on each keyup event from the input field. Code $(inputTextField).keyup(function() { / ...

The response data from Axios cannot be stored using useState hook

Struggling with fetching data from my express backend and MySQL database to display on my react frontend using axios. However, I'm facing issues when trying to update the fetched data using the useState hook. Here is how my frontend function is struc ...

Are the digest cycle and dirty checking synonymous terms?

I have a question that's been bugging me lately. Can you clarify for me if the digest loop (also known as digest cycle) in AngularJS is synonymous with dirty checking? And if they are different, could you please explain the distinctions between them? ...