Selected options sum using JS

B4B1B4B1 Community Member Qubie ✭
edited January 17 in Custom Code

Selected options sum using JS

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;


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;
        var productPrice = parseFloat(innerProductText.split("€")[1]);  
        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.attr('title', 'Next Category');



-> This is the text description o each option choice:

product A

-> This is the code placed in the HTML view:
select products:

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

Sign In to Comment