1

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>
4
  • Have you tried anything in Vue.js or vanilla JS? Commented May 22, 2020 at 1:16
  • Yes, I tried with some mounted functions and lifecycle hooks and got nothing. Commented May 22, 2020 at 1:17
  • Can you show us that code? Commented May 22, 2020 at 1:17
  • I got rid of it because it didn't work. I'm currently looking through VueJS docs for other ways to achieve this. Commented May 22, 2020 at 1:21

1 Answer 1

1

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>

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for your input, @Kalimah. Is there also a way I could grab the values from the inputs themselves instead of the array?
Although its against vue.js pattern to do this but you can access the DOM using document.querySelectorAll(). Or use can add ref directive to each input and access it from vue using this.$refs

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.