Place this script in the source of the first multiple-choice. It will:
- place a listener on the check-boxes in that question
- randomize the checked target codes as you describe above
- load the short-text with the selected random code
- check the corresponding box in the second multiple-choice (I change the codes in that question so they match the first question)
Code:
<script type="text/javascript" data-author="Tony Partner">
$(document).on('ready pjax:scriptcomplete',function(){
// Identify the questions
var qID = '{QID}';
var thisQuestion = $('#question'+qID);
var textQuestion = thisQuestion.nextAll('.text-short:eq(0)');
var nextMultiOpt = thisQuestion.nextAll('.multiple-opt:eq(0)');
var nMOID = nextMultiOpt.attr('id').replace(/question/, '');
// Identify the sub-question codes to target
var sqCodes = [4, 5, 9];
// Listener on the checkboxes
$(':checkbox', thisQuestion).on('change', function(e) {
// Reset the hidden questions
$(':text', textQuestion).val('');
$(':checkbox', nextMultiOpt).prop('checked', false).trigger('change');
// Build an array of checked codes (use all if none are checked)
var checkedCodes = [];
$.each(sqCodes, function(i, val) {
if($(':checkbox[id$="X'+qID+val+'"]').is(':checked')) {
checkedCodes.push(val);
}
});
var randomCodes = sqCodes;
if(checkedCodes.length > 0) {
randomCodes = checkedCodes;
}
// Randomize the codes
shuffleArray(randomCodes);
// Load the hidden questions
var selectedCode = randomCodes[0];
$(':text', textQuestion).val(selectedCode);
$(':checkbox[id$="X'+nMOID+selectedCode+'"]', nextMultiOpt).prop('checked', true).trigger('change');
});
});
function shuffleArray(array) {
for (var i = array.length - 1; i > 0; i--) {
var j = Math.floor(Math.random() * (i + 1));
var temp = array[i];
array[i] = array[j];
array[j] = temp;
}
return array;
}
</script>
Sample survey attached: