Answer the question
In order to leave comments, you need to log in
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
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);
}
}
})
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question