R
R
r_g_b_a2020-02-16 22:18:54
Vue.js
r_g_b_a, 2020-02-16 22:18:54

How to sum all values ​​of checked checkboxes?

Hello.
Given a list of checkboxes https://jsfiddle.net/zt8hL9w7/ when selected, the sum of their values ​​is displayed. But I need the value of each item to be pre-calculated according to its own formula. For example, when Checkbox 1 is selected, its value must be multiplied by the value of some input on the page, and this result should be passed to the summation function, and the same for the rest.
Where in the code can these functions be written?

And I also noticed that if in my example checkboxes have the same values, then they are marked all together as a group. How to fix it?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
K
Klein Maximus, 2020-02-16
@r_g_b_a

https://jsfiddle.net/KleinMaximus/sohzx029/

A
Alex, 2020-02-16
@Kozack Vue.js

You can use getters. For example something like this:

class CheckBoxCalc {
  constructor(text, callback) {
  	this.text = text
  	this.cb = callback
  }
  
  get value() {
  	return this.cb()
  }
}


new Vue({
  el: "#app",
  data: {
  	checkedNumbers: [],
    checkbox: [
    	new CheckBoxCalc('Checkbox 1', () => 10),
      new CheckBoxCalc('Checkbox 2', () => Math.floor(Date.now() / 10000000)),
      new CheckBoxCalc('Checkbox 3', () => Math.floor(Math.random() * 100)),
    ]
  },
  computed: {
  	sum() {
    	return this.checkedNumbers.reduce((acc, index) => {
      	return acc + this.checkbox[index].value
      }, 0);
    }
  }
})

It looks a little collective farm, but there you yourself will bring it to mind

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question