Reputation: 17
I want to loop over my code and grab the value of each form input because I want to display a total score and a severity score from my form inputs. The total score will calculate how many symptoms are present (0-3) and the severity score will calculate the severity of each symptom the user drags the slider to (0-18). I want each score to change as the user drags each slider.
HTML:
<div class="field">
<label class="label">Headache</label>
<input
v-model="form2.headache"
name = "headache"
type="range"
min="0" max="6"
class="slider"><span v-text="form2.headache"></span>
</div>
<div class="field">
<label class="label">"Pressure in head"</label>
<input
v-model="form2.pressureInHead"
name = "pressureInHead"
type="range"
min="0" max="6"
class="slider"><span v-text="form2.pressureInHead"></span>
</div>
<div class="field">
<label class="label">Neck Pain</label>
<input
v-model="form2.neckPain"
name = "neckPain"
type="range"
min="0" max="6"
class="slider"><span v-text="form2.neckPain"></span>
</div>
<div class="field">
<p>Total number of symptoms: {{ total }}</p>
<p>Symptom Severity Score: {{ severity }}</p>
</div>
JS:
data: {
form2: {
headache: 0,
pressureInHead: 0,
neckPain: 0,
}
}
If the user dragged headache to 4, pressure in head to 0, and neck pain to 3, the total score would display 2 because 2 symptoms (headache and neck pain) are present and the severity score would display 7 (4+0+3).
I have tried writing computed functions, but I am not sure what to write in the for-loop. I can only find iterating over lists and arrays online. This is what I've tried writing to calculate the total:
computed: {
total() {
var totalScore = 0
for(value in this.data.form2) {
totalScore+=Number(value)
}
return totalScore
},
}
Upvotes: 1
Views: 55
Reputation: 164733
You'll want two computed functions, one for the total symptoms and another for the severity.
You can do your calculations using a reduce job. The first adds 1
for each symptom in form2
over 0
. The second sums the values.
computed: {
totalSymptoms () {
return Object.values(this.form2).reduce((sum, val) =>
sum += (val > 0) ? 1 : 0, 0)
},
totalSeverity () {
return Object.values(this.form2).reduce((sum, val) => sum += Number(val), 0)
}
}
and use them in your template like
<div class="field">
<p>Total number of symptoms: {{ totalSymptoms }}</p>
<p>Symptom Severity Score: {{ totalSeverity }}</p>
</div>
Upvotes: 1