Prevent survey progression via JavaScript | XM Community
Skip to main content

In my survey I have a constant sum matrix table with 2 columns and the total for the 2 columns must equal the value given for a previous question, e.g.:

 

question_0: how many items did you buy? ; answer_0 = 10

question_1:

  for you for your friend
apples a b
oranges c d
total e f

I only want to allow the survey to progress when e + f = 10. I think the default sum validation can only look at e and f individually and check if these equal 10?

 

I have added some JavaScript inside the addOnPageSubmit method and I can return a browser alert when the totals don’t match, but the survey still progresses to the next page when the alert is dismissed.

 

Is there anything I am doing wrong, or missing?

 

Thanks!

 

Qualtrics.SurveyEngine.addOnPageSubmit(function() {
// Function to validate the totals
function validateTotal() {
// Retrieve the embedded data field value
const s17_01 = parseFloat('${e://Field/s17_01}');

// Retrieve the values entered by the respondent
const inPatientTotal = parseFloat(document.getElementById('QID40~1_Total').value) || 0;
const outPatientTotal = parseFloat(document.getElementById('QID40~2_Total').value) || 0;

// Calculate the combined total
let allPatientTotal = inPatientTotal + outPatientTotal;

// Check if the totals match
if (s17_01 !== allPatientTotal) {
// Show an alert if the totals do not match
alert('Totals are not correct.');
return false; // Return false to prevent page submission
}
return true; // Return true if the totals match
}

// Check the result of validateTotal before submitting the page
if (!validateTotal()) {
// Prevent page submission if validation fails
return false;
}
});

 

Be the first to reply!

Leave a Reply


OSZAR »