Javascript code to set validation using the previous selected options and current rank oder | XM Community
Skip to main content

Hi all,

 

I am new to javascript. The validation rule I want is that respondents pass current Rank Order if the options ranked in the last two positions of the current Rank Order question are the same as the options selected in the previous Multiple Choice question (both questions have identical options and corresponding recode values). If this condition is not met, the respondent should see a warning (like a forced response message in red text below the question) when they click next. How can this be implemented in JavaScript and html view? Below is the code Qualtrics Support AI Assistant gave me (and I replace QID with ones in my project) but did not work. I greatly appreciate for any help!

Html view is

<p>Please rank the following options:</p>
<div id="warningMessage" style="color: red; display: none;">Please ensure the last two ranked options match the selected options in the previous question.</div>

 

Javascript is below (no function in addonload and addOnUnload)

Qualtrics.SurveyEngine.addOnReady(function() {
// Get the question IDs
var mcQuestionId = "QID1"; // Replace with the actual ID of the Multiple Choice question
var roQuestionId = "QID2"; // Replace with the actual ID of the Rank Order question

// Get the warning message element
var warningMessage = document.getElementById("warningMessage");

// Function to check the condition
function checkCondition() {
var mcSelectedValues = s];
var roRankedValues = s];

// Get selected recode values from the Multiple Choice question
jQuery("#" + mcQuestionId + " .q-checked").each(function() {
mcSelectedValues.push(jQuery(this).find("input").val());
});

// Get ranked recode values from the Rank Order question
jQuery("#" + roQuestionId + " .ranked").each(function() {
roRankedValues.push(jQuery(this).find("input").val());
});

// Check if the last two ranked values match the selected values
var lastTwoRankedValues = roRankedValues.slice(-2);
var conditionMet = mcSelectedValues.every(value => lastTwoRankedValues.includes(value));

// Show or hide the warning message
if (!conditionMet) {
warningMessage.style.display = "block";
} else {
warningMessage.style.display = "none";
}

return conditionMet;
}

// Add event listener to the Next button
jQuery("#NextButton").click(function(event) {
if (!checkCondition()) {
event.preventDefault(); // Prevent the form from submitting
}
});

// Add event listener to the Rank Order question
jQuery("#" + roQuestionId + " .ranked").on("change", function() {
checkCondition();
});
});
Be the first to reply!

Leave a Reply