Calculate the total sum of input values containing data retrieved from the backend once the component data has been loaded and all backend data has been fetched in VueJS

My challenge involves a table that is filled with inputs located within table cells. All these inputs have the same class, regardless of how many are retrieved. My goal is to access the values of each input, add them together, and then place the sum in another input after the backend data has been fetched when the component loads. I've accomplished this using vanilla JS and jQuery, but I'm struggling to find a way to do it with VueJS given that the data is fetched differently. How can I achieve this using VueJS?

Here's an example of the HTML structure:

<input class=".inputs" value="2"></input>
<input class=".inputs" value="2"></input>
<input class=".inputs" value="2"></input>
<input class=".inputs" value="2"></input>

<input class=".result" value="0"></input>

Answer №1

In order to display input values and calculate the total, you can create a data property in Vue.js to hold the input values. By watching for changes in the array, you can update the result input accordingly. Here's an example:

new Vue({
  el: "#app",
  data: {
    input_array: [2, 2, 2, 2],
  },
  mounted: function() {
    // Update array values
    this.input_array = [5, 3, 4, 6];
  },
  watch: {
    input_array: function(newValue) {
      // Calculate total on every array change
      const total = this.input_array.reduce((acc, val) => acc + val);
      this.$refs.result.value = total;

    }
  }
})
input {
  display: block;
  clear: both;
  padding: 0.3em;
}

.result {
  margin-top: 1.5em;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id='app'>
  <input class="inputs" :value="i" v-for='i in input_array'>

  <input class="result" value="0" ref='result'>
</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

Connect Promise.all() with an array of identification numbers

I'm fairly new to working with Promises and I have a question regarding linking the results of `Promises.all()` to unique IDs for each promise once they resolve. Currently, I am making requests to a remote server and retrieving data for each request. ...

Storing references to the DOM elements external to the rendering component

Just diving into the world of Electron + Typescript, so please bear with me. Currently, I'm experimenting with what can be achieved within Electron. Issue: My goal is to manipulate DOM elements outside of the renderer. I pass a button as a parameter ...

The Next.js error occurred due to the call stack size exceeding the maximum limit, resulting in

I am currently developing a duplicate of the Notion app using shadc-ui's components [https://ui.shadcn.com/] for the (landing)- router and _components integration. Check out the image below: https://i.sstatic.net/rOq5C.png layout.js : import " ...

Tips for incorporating PHP $_SESSION data into a JavaScript file

What I've been doing is using $_SESSION['siteRoot'] to store the root address of my website (since it's part of a framework and can vary depending on how the site is accessed). The challenge now is incorporating this value into some of ...

What is the best way to conceal a dynamically-loaded element on a webpage?

I wrote a script that utilizes AJAX to fetch data from a PHP file named names.php. Later in the script, I used jQuery's $(document.ready(function(){}); to attempt hiding a div when the DOM is loaded. Strangely, the $("div").hide() function isn' ...

The Bootbox dialog.modal('hide') function is not effectively hiding the modal

I am facing an issue with bootbox.js modals. I am trying to utilize bootbox.dialog to pause the UI while an Ajax request is in progress and awaiting a response. Everything works fine when using dialog.modal('hide'); within bootbox.alert with conf ...

VueJS encountered an issue while displaying the image

I am facing an issue with VueJS while trying to populate my index.html with images fetched from the iTunes API. The API returns a URL to an image, but I am struggling to render them on my webpage. The 'item' variable holds the object data. Initi ...

Is it possible for me to pass a value through props that is not currently stored in the state?

Within the realm of Reactjs, imagine a scenario where there exists a <Parent> component containing state and a variable named foo, which is either 'global' or local to Parent. The question arises: Can we pass foo as props using <Child v ...

Loading a page with a subtle fade-in effect using jQuery

Looking to add some jQuery functionality to my navigation menu in order to have the page wrapper fade in and out when a main nav link is clicked. While the code itself is functioning properly, I am encountering a couple of issues: There is a brief flash ...

Personalizing data structure fields in sanity.io

In the Sanity Studio schema, I created an object type with one field that is dependent on another. If the "all" field is checked true, then the "date" field should be hidden or disabled. However, I am unsure of how to implement this. I have searched for e ...

In the world of web development with JavaScript, jQuery, and EasyUI, we often encounter situations where the parameter

function formatData_original() { // convert obj_num2.formatter = function(value, rec) { var baseStr='&nbsp;&nbsp;' + rec.s_date + '<a class="easyui-linkbutton" href="javascript:void(0);" plain= ...

The class name remains unchanged despite the change in value

I am currently working on a webpage that features two interactive tabs. The goal is to have one tab highlighted as "active" while the other remains inactive when clicked, and then switch roles when the other tab is selected. Below is the code snippet I ha ...

How to pass children and additional arguments to a React/NextJS component

Currently, I am utilizing NextJS with a global PageLayout wrapper that is responsible for setting the head and creating the wrapping divs for all my pages. However, I am facing a challenge as I attempt to set a custom title tag for each page. This task req ...

Obtaining the TemplateRef from any HTML Element in Angular 2

I am in need of dynamically loading a component into an HTML element that could be located anywhere inside the app component. My approach involves utilizing the TemplateRef as a parameter for the ViewContainerRef.createEmbeddedView(templateRef) method to ...

Ensure that each item rendered in a VUE.js v-for loop is distinct and not repetitive

I have obtained a JSON formatted object from a Web API that contains information about NIH funding grants. Each grant provides a history of awards for a specific researcher. My goal is to display only the latest award_notice_date for each unique project ...

Tips for enabling custom elements in Firefox

I am struggling with getting a basic custom element example to work in Firefox. It functions properly in Chrome, but not in Firefox. Is there a way to make it work in Firefox, possibly using some sort of polyfill instead of Polymer? I have already tried e ...

CSS switch status toggle

Here's my code for a toggle switch from . I'm trying to change the label before the switch/checkbox to display "checked" or "not checked" based on the toggle state. When I click on the label, it changes the switch but not the text. JavaScript: ...

Sending an array and an object simultaneously through a single ajax request

I previously inquired about passing an object to an ajax request for my rest service. Now I am wondering if it's possible to pass both an array and an object within a single ajax request. Any insights on this matter would be greatly valued. ...

Transform CSS into React.js styling techniques

My current setup involves using Elementor as a REST Api, which is providing me with a collection of strings in React that are formatted like this: selector a { width: 189px; line-height: 29px; } Is there a tool or library available that can conver ...

Is it necessary for vertex labels to be distinct within a graph?

I am currently developing a browser-based application that allows users to create graphs, manipulate them, and run algorithms on them. At the moment, each vertex is represented by a unique positive integer. However, I am considering implementing labeled ve ...