grahamfk45c
grahamfk45c

Reputation: 83

VueJS Add up the values of inputs that are populated with backend data values after the component data is loaded and backend data is fetched?

So I have a table that gets populated with inputs that are held within table cells. No matter how many inputs are retrieved, these particular inputs all have the same class. I need to find a way to target the values of each of these inputs, add those up, and then place that value into another input after the backend data has been fetched upon component load/mount. I can do this with vanilla JS and jquery, but I apparently need to go a different route with VueJS and this data being fetched. How can I achieve this in VueJS?

HTML EXAMPLE

<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>

Upvotes: 1

Views: 32

Answers (1)

Kalimah
Kalimah

Reputation: 11447

Typically, you can add a data property that holds values of input. Then watch the array changes to add them and show them in result input. Here is 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) {
      // Values will be added 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>

Upvotes: 1

Related Questions