Calculating the sum of integer values from v-models in Vue 2

I am currently working with Nuxt version 2.8.1

There are a total of 100 input fields in my form, all of which are number inputs.

My goal is to calculate the sum of all these numbers to get the total.

This is what I have tried so far:

computed: {
     total() {
       return this.form.one + this.form.two
     }
}

Expected Outcome:

5 + 5 = 10

Actual Output Received:

5 + 5 = 55

If I leave the value for 'two' empty, I get a result of 5null

I cannot seem to figure out why this is happening.

Answer №1

It treats them as strings and combines them together as shown, so it's best to convert them to integers using a Number object like this:

 return Number(this.form.one) + Number(this.form.two)

To optimize efficiency, I suggest using the reduce function especially when dealing with multiple inputs:

 return Object.values(this.form).reduce((a,c)=> {
       return a+Number(c);                 
       },0)

For instance:

let form = {
  one: 45,
  two: 5,
  three: 7
}

let sum = Object.values(form).reduce((a, c) => {
  return a + Number(c);
}, 0)

console.log(sum)

Answer №2

Assuming that your parameter is in the form of user input, you can consider using a modifier to resolve this issue (https://v2.vuejs.org/v2/guide/forms.html#number)

HTML Snippet

<input v-model.number="form.one" ></input>
<input v-model.number="form.two" ></input>

JavaScript (can remain unchanged or use the reduce method)

computed: {
     total() {
       return this.form.one + this.form.two
     }
}

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

How a Dynamic Icon Component in NextJS/React can disrupt Jest testing

Hello there! I'm a new member of this community, and usually I can find answers to my questions by searching. However, this time around, I need some help. My Current Setup I am using NextJS solely as a framework application without utilizing its API ...

Looking to tweak the date format in a Vue.js template?

I received the following format: 2019-01-08T11:11:00.000Z However, I need it to be in this format: 2019-01-08 Does anyone know how to achieve this date formatting without using the moment package? ...

Google Maps is experiencing difficulties with loading

Important Note: I have decided to create a new question regarding this issue. I recently inquired about the Google Maps rendering problem. The response seemed straightforward, but my code appears as follows: var map; function initialize() { var m ...

The jQuery autocomplete feature seems to be malfunctioning and not displaying

Here is the code snippet I am working with: <div class="input-group"> <form method="POST" id="id1"> <input id="id2" type="text" style="min-width: 370px;" class="form-control" placeholder="..."> </form> </div> ...

Utilizing Database values in .css files with Vue.js and TypeScript

I am currently working on extracting a color value from the database and applying it to my external .css files. I have searched extensively online but haven't found a satisfactory solution yet. Here is the JavaScript code snippet: createBackgroundHead ...

What are some ways to create a multi-select event?

Check out my HTML code: <select id="specific_choice14" multiple="multiple"> <option value="Shampoing">Shampoing</option> <option value="Après Shampoing">Après Shampoing</option> <option value="Mask"> ...

The previous method of using `vue/compiler-sfc ::v-deep` as a combinator has been phased out. Instead, opt for the new syntax `:deep(<

When developing with Nuxt 2, I am encountering numerous [@vue/compiler-sfc] ::v-deep usage as a combinator has been deprecated. Use :deep(<inner-selector>) instead. errors when running npm run dev. After attempting to resolve the issue by changing a ...

JavaScript: The variable `scopes` is declared

I'm completely new to JavaScript. Can anyone help me understand why this code isn't working, and what changes I need to make to fix it? function getResults(keywords) { foo.foo = function() { var bar = foo.getSomeText; // ...

In JavaScript, you can use the document.cookie property to delete specific cookie values identified by their names and values

Within my JavaScript code, I am working with a cookie that contains multiple names and values: "Token=23432112233299; sessionuid=abce32343234" When I download a file from the server, a new cookie is added to the document, resulting in the following cooki ...

In my code, I never use the term "require", yet webpack continues to generate the error message "require is not defined."

I am in the process of developing an electron app using react. To run the development version, I use the following command: webpack-dev-server --hot --host 0.0.0.0 --port 4000 --config=./webpack.dev.config.js Displayed below is the webpack.dev.config.js ...

Utilizing AJAX and PHP to create a dynamic like button function

Is there a way to make the like number increase without refreshing the page when the like button is clicked? Here's my current code: <script type="text/javascript> jQuery(document).ready(function ($) { $('body').on( 'cli ...

Angular element gives back an undefined value

Why does my second function getRatings() return undefined in console.log, even though the first API function is working fine and logging data without any issues? I have a service file with two functions that return API and array data. In the constructor ...

How can I capture the 'ended' event from an HTML5 video tag using Ember in a controller?

I am having an issue with an hbs file that contains an html5 video tag: <video id="externalVideo" controls loop> <source src="../assets/videos/test.mp4" type="video/mp4"> Your browser does not support HTML5 video. </video> I am ...

Is it possible to modify the geometry in Three.js to match the texture?

Currently, I am immersed in a Three.js project that involves integrating multiple images into a 3D space. My approach so far has been to directly use these images as textures on planes. However, the challenge lies in the fact that these images vary in heig ...

KnockoutJS fails to create observables out of JSON data

I created a basic application that retrieves JSON data from the server using C# code. public JsonResult Read() { var products = db.Products; return Json(GetProducts(), JsonRequestBehavior.AllowGet); } public IEnumerable<Product> GetProducts ...

Cannot Properly Import JSX Elements in TailwindCSS and React

I am facing an issue with importing a JSX Element into my main file, App.js. The element I want to load is in a separate file called element.js and contains the following code: const element = () => { return ( <div className="text-gr ...

How can you implement a switchable theme feature similar to Twitter on your website?

As a beginner programmer and college student with limited design knowledge, I am working on creating a microblogging website similar to Twitter. I noticed that some websites use pre-loaded styles or themes without separate CSS files. I am unsure of how t ...

Is it accurate to say that the XSS source < > is correct?

I managed to locate the code for preventing XSS attacks. private String cleanXSS(String value) { value = value.replaceAll("<", "& lt;").replaceAll(">", "& gt;"); value = value.replaceAll("\\(","& #40;").replaceAll(" ...

Identifying issues in jQuery code - What could be causing this error?

My jQuery code is not responding at all, not even showing an error! I'm not sure why, but here is the jQuery Code I'm using: /* This part is working fine */ $(".add-blog .blog-add-form .add-article .input-group select").on("change", function() ...

What is the best way to attach to the beforeSubmit event of a dynamically loaded AJAX form in Yii?

Recently, I encountered an issue with dynamically loading a form via AJAX and attempting to bind the beforeSubmit event. Strangely, the event didn't seem to work as expected, causing the form to submit and the browser to navigate to a new page. This b ...