Selected options sum using JS | XM Community
Question

Selected options sum using JS

  • 17 January 2020
  • 1 reply
  • 73 views

Userlevel 1
Badge +1
I created a multiple choice question with a javascript code that sums the total of each option selected. However, I am having two issues:
1. After selecting some choices (normally happen when the fifth option is selected) the code does not sum correctly anymore, it actually decreases the amount of the last option selected.
2. Sometimes when you select a product in the total sum show a sign of - in front of the total value. E.g., €-1.69

->This is the code I am using to sum the options selected:

var totalPrice = 0;

Qualtrics.SurveyEngine.addOnload(function()
{

document.getElementById('totalSpend').innerHTML = "Total amount spent: €"+totalPrice;
document.getElementById('totalSpend').style = "border: none;font-size: 20pt; font-weight: bold";

this.questionclick = function(event,element)
{
var innerProductText = element.innerText;
if(innerProductText){
var productPrice = parseFloat(innerProductText.split("€")[1]);
console.log(element);
if(element.classList[1] == 'q-checked' || element.classList[2] == 'q-checked' || element.checked){
totalPrice += productPrice;
} else {
totalPrice -= productPrice;
}
totalPrice = Math.round(totalPrice*100)/100;

document.getElementById('totalSpend').innerHTML = "Total amount spent: €"+totalPrice;
}
}
});

Qualtrics.SurveyEngine.addOnReady(function() {
var newName = 'Check your products'; //Update - New Next Button label
var lastLoopOnly = true; //Last loop only? Value doesn't matter to non-loops
//No changes below
if(!lastLoopOnly || "${lm://CurrentLoopNumber}" == "${lm://TotalLoops}") {
var nb = jQuery('#NextButton');
nb.val(newName);
nb.attr('title', 'Next Category');

}
});

-> This is the text description o each option choice:
<div style="text-align: center;" id="1.05">product A<br/>€1.05</div>

-> This is the code placed in the HTML view:
<span style="font-weight: 700;">select products: <br></span><div id="totalSpend"></div>

Would someone know how to fix that?
Thank you for the help!

1 reply

Badge +2

Did you ever get a response to this or come up with a solution? I am trying to accomplish the same thing.
Thanks in advance!

Leave a Reply