Search code examples
javascriptdynamicqualtrics

Qualtrics Dynamic Sum of Multiple Tables Question


I currently have two table that each give a calculated total. I'm currently trying to add a function that will allow me to see the sum of these two totals.

Qualtrics.SurveyEngine.addOnload(function()
{
  var p1 = "${q://QID4/TotalSum}";
  var p2 = "${q://QID10/TotalSum}";
  document.getElementById("myBtn").addEventListener("click", function() {
    myFunction(p1,p2);
  });
  function myFunction(a,b) {
    var result = Number(a)+Number(b);
    document.getElementById("demo").innerHTML = result;
  }
});

Doing this I am able to get the sum value, however only after I go to the next page and then back to this page. Is there a way to make it so that I can get the sum value without having to change pages.

I'm very new to this and any help would be appreciated, thanks.


Solution

  • p1 and p2 only get updated when you load the page. Assuming both QID4 and QID10 are on the same page as myBtn, you should get the values of p1 and p2 inside the event listener instead of using piped values.

    The exact code depends on the format of the constant sum questions and what else is on the page, but it would be something like:

    Qualtrics.SurveyEngine.addOnload(function()
    {
      var p1 = jQuery(".SumTotal input:first"); //find total elements
      var p2 = jQuery(".SumTotal input:last");
      myFunction(p1.val(),p2.val()); //initialize total on page load
      document.getElementById("myBtn").addEventListener("click", function() {
        myFunction(p1.val(),p2.val());
      });
      function myFunction(a,b) {
        var result = Number(a)+Number(b);
        document.getElementById("demo").innerHTML = result;
      }
    });
    

    EDIT BASED ON COMMENTS:

    Once you get above two, I would use a loop:

    Qualtrics.SurveyEngine.addOnload(function()
    {
      var totals = jQuery(".SumTotal input"); //find total elements
      myFunction(totals); //initialize total on page load
      document.getElementById("myBtn").addEventListener("click", function() {
        myFunction(totals);
      });
      function myFunction(tots) {
        var result = 0;
        tots.each(function() { result += Number(this.value); });
        document.getElementById("demo").innerHTML = result;
      }
    });