Javascript validation | XM Community
Skip to main content

I am trying to add a validation where I verify that the mean of the distribution provided by the participant in a constant sum question is equal to an embedded data field. I managed to get the validation to work and display a message if the provided distribution does not match the desired average; however, I am struggling to get the survey to stop proceeding to the next page if the validation fails.

 

Here is the code I have so far:
 

Qualtrics.SurveyEngine.addOnPageSubmit(function(type) {
if (type == "next") { // Only run this if the user clicks "Next"

// Define the required value from the embedded data
var requiredStars = parseFloat(Qualtrics.SurveyEngine.getEmbeddedData("stars"));

// Fetch values from input fields (assuming there are 5 fields)
var questionId = this.getQuestionContainer().id;
var value1 = parseFloat(jQuery("#" + questionId + " inpututype='text']").eq(0).val()) || 0;
var value2 = parseFloat(jQuery("#" + questionId + " inpututype='text']").eq(1).val()) || 0;
var value3 = parseFloat(jQuery("#" + questionId + " inpututype='text']").eq(2).val()) || 0;
var value4 = parseFloat(jQuery("#" + questionId + " inpututype='text']").eq(3).val()) || 0;
var value5 = parseFloat(jQuery("#" + questionId + " inpututype='text']").eq(4).val()) || 0;

// Apply the formula: box1 * 1 * 0.01 + box2 * 2 * 0.01 + etc.
var calculatedValue = (value1 * 1 * 0.01) + (value2 * 2 * 0.01) + (value3 * 3 * 0.01) + (value4 * 4 * 0.01) + (value5 * 5 * 0.01);

// Round the result to the nearest whole number
var roundedCalculatedValue = Math.round(calculatedValue);

// Validate if the calculated value matches the required stars value
if (roundedCalculatedValue !== Math.round(requiredStars)) {
alert("The calculated value of your entries must equal " + requiredStars);
event.preventDefault(); // Prevent form submission
return false; // Prevent further submission
}

// If everything is fine, allow the form to submit
return true;
}
});



Would really appreciate some help!

You’ll need to change your approach. Use addOnReady, disable the Next button, and recalculate each time a value changes. If the recalculated value meets the criteria enable the Next button.  


Leave a Reply