Constant Sum on Side By Side | XM Community
Skip to main content

Hello all,

I’m trying to add a constant sum type column into a side-by-side question. I’ve tried using code from various posts on this forum and amending it to my needs, but I’m yet to be successful. Would really appreciate some help!

 

I have a four column side-by-side question. I would like the very bottom row to show the total sum of the far right column. I would like the other columns’ fields on the bottom row to ideally not be there, or at least disabled. 

 

 

 

Current code is below that I’ve adapted from this previous post.

If anyone could tell me where I’m going wrong I’d really appreciate it! 

 

---------------------------------------------------------

 

Qualtrics.SurveyEngine.addOnReady(function () {
  // Use jQuery without conflicts (Qualtrics requires this)
  var $jq = jQuery.noConflict();

   // Hide the last dropdown (select) in specific columns
 $jq('.SBS1 select:last').hide(); // hide last select in Column 1
 $jq('.SBS2 select:last').hide(); // hide last select in Column 2
 $jq('.SBS3 select:last').hide(); // hide last select in Column 3

  // Initialize the "total" value in Column 4 as 0
  var $sum = 0;
   $jq('.SBS4 input:last').val($sum); // set the last input in Column 4 = 0
    
  // Helper function: safely turn text into a number
  function getVal(val) {
    var num = parseInt(val); // try converting to an integer
    if (isNaN(num)) {
      num = 0; // default to 0 if not a number
    }
    return num;
  }

  // Whenever a value changes in Column 4 (except the last "total" box)...
  $jq('.SBS4 input')
    .not(':last') // exclude the last box (the "total")
    .change(function () {
      var $sum = 0; // reset sum before calculating

      // Loop through all Column 4 inputs (except last one)
      $jq('.SBS4 input')
        .not(':last')
        .each(function () {
          // Add up their numeric values
          $sum += +getVal($jq(this).val());
        });

      // Update the last input in Column 4 with the total
      $jq('.SBS4 input:last').val($sum);
    });
});
 

 

RESOLVED

 

I had more than one side-by-side question on the page. This code uses ‘last’, so it was finding the last instance on the page, rather than in the question. Have updated the code to just be looking at the question I need it to, and it now works!

 

  // Limit selectors to THIS question only
  var $qContainer = $jq(this.getQuestionContainer());


Leave a Reply