Javascript with multiple choice question, shopping cart scenario | XM Community
Skip to main content

Hello everybody,

I am new to javascript. I am trying to imitate a shopping cart scenario. I have a multiple choice question where people are shown several products with price/kg. They are asked to select as many products as they prefer to buy. I am trying to dynamically show the amount of money they are spending based on the options they select at the bottom of the page, similar as in online purchases. After the multiple choice question I added a text question and under “Question behaviour” I wrote the script in the javascript. However, it is not working as the question which should show the total amount of money spent is not being updated. Thankk you very much if you respond!!!

 

The script is:

Qualtrics.SurveyEngine.addOnload(function() {
    // Specify the question ID for the Multiple Choice question
    var multipleChoiceQuestionId = 'QID1'; // Replace with your actual question ID

    // Mapping of monetary values to choices
    var monetaryValues = {
        '1': 4.25,
        '2': 2.10,
        '3': 1.85,
    };

    // Add an event listener to the Multiple Choice question
    jQuery("#" + multipleChoiceQuestionId + " input").on("change", function() {
        updateTotalAmountSpent();
    });

    // Function to update and display the total amount spent
    function updateTotalAmountSpent() {
        var totalAmountSpent = calculateTotalAmountSpent();
        console.log("Total Amount Spent: $" + totalAmountSpent.toFixed(2));

        // Display the total amount spent within a Text Entry question
        jQuery("#EXP_BAKERY_TotalAmountSpent").val("You have spent a total of $" + totalAmountSpent.toFixed(2));
    }

    // Function to calculate the total amount spent
    function calculateTotalAmountSpent() {
        var totalAmountSpent = 0;

        // Loop through each selected choice and add its monetary value to the total
        jQuery("#" + multipleChoiceQuestionId + " input:checked").each(function() {
            var choiceId = jQuery(this).attr("id");
            totalAmountSpent += monetaryValuesuchoiceId];
        });

        return totalAmountSpent;
    }

    // Initialize and display the total amount spent
    updateTotalAmountSpent();
});

Qualtrics.SurveyEngine.addOnReady(function()
{
    /*Place your JavaScript here to run when the page is fully displayed*/

});

Qualtrics.SurveyEngine.addOnUnload(function()
{
    /*Place your JavaScript here to run when the page is unloaded*/

});

Be the first to reply!

Leave a Reply