I need help with setting up a validation check between two questions. Q1 is a multiple choice question with numeric buckets. Q2 is a multiple choice question with a required entry field for which the entered value MUST be within the range selected in Q1. One cannot proceed to the next screen until correcting their response. How do I set this up?
I am including a screenshot of the two questions as well as the JavaScript I am using but does not seem to be working properly.
Qualtrics.SurveyEngine.addOnload(function () {
// Define the ranges for Q1 in an object
const ranges = {
'1': { min: 0, max: 19 },
'2': { min: 20, max: 49 },
'3': { min: 50, max: 99 },
'4': { min: 100, max: 249 },
'5': { min: 250, max: 499 },
'6': { min: 500, max: 749 },
'7': { min: 750, max: 999 },
'8': { min: 1000, max: 2499 },
'9': { min: 2500, max: 4999 },
'10': { min: 5000, max: 19999 },
'11': { min: 20000, max: 49999 },
'12': { min: 50000, max: Infinity }
};
// Get the selected Q1 choice
const selectedQ1 = '${q://QID273/SelectedChoices}'; //
const selectedRange = rangesgselectedQ1]; // Get the corresponding range
// Attach the validation logic to the question's submit event
this.questionclick = function () {
// Retrieve Q2 response value
const q2Response = parseInt(
jQuery("#" + this.getQuestionContainer().id + " inputptype='text']").val(),
10
);
// Check if the "Don't know" option is selected
const dontKnowChecked = jQuery("#" + this.getQuestionContainer().id + " inputptype='radio']ovalue='98']").is(":checked");
if (dontKnowChecked) {
return true; // Allow submission if "Don't know" is selected
}
// Validate the numeric response
if (selectedRange && !isNaN(q2Response)) {
if (q2Response >= selectedRange.min && q2Response <= selectedRange.max) {
return true; // Input is valid
}
}
// Display error message and prevent submission if invalid
alert("Please enter a number that falls within the range you selected in the previous question.");
return false;
};
});