- Posts: 194
- Thank you received: 69
Ask the community, share ideas, and connect with other LimeSurvey users!
<script type="text/javascript" charset="utf-8"> $(document).on('ready pjax:scriptcomplete',function(){ // Define the weightings by sub-question code var weights = { 'SQ001': 50, 'SQ002': 15, 'SQ003': 35 } // Identify this question var qID = '{QID}'; var thisQuestion = $('#question'+qID); var previousQuestion = thisQuestion.prevAll('.multiple-opt:eq(0)'); var prevID = $(previousQuestion).attr('id').replace(/question/, ''); // Hide this question thisQuestion.hide(); // Listener on the checkboxes $('input:checkbox', previousQuestion).on('change', function(e) { // Reset this question $('.checkbox-item input:hidden', thisQuestion).val(''); $('.checkbox-item input:checkbox', thisQuestion).prop('checked', false).trigger('change'); // Only one item checked if($('input:checkbox:checked', previousQuestion).length == 1) { var checkedCode = $('input:checkbox:checked', previousQuestion).attr('id').split('X'+prevID)[1]; var thisItem = $('.question-item[id$="X'+qID+checkedCode+'"]'); $('input:hidden', thisItem).val('Y'); $('input:checkbox', thisItem).prop('checked', true).trigger('change'); } // Multiple items checked else if($('input:checkbox:checked', previousQuestion).length > 1) { // Build a weighted array of the checked items var sqCodesArr = []; $('input:checkbox:checked', previousQuestion).each(function(i) { var checkedCode = $(this).attr('id').split('X'+prevID)[1]; for (i = 0; i < weights[checkedCode]; i++) { sqCodesArr.push(checkedCode); } }); // Randomize the array shuffleArray(sqCodesArr); // Check the box corresponding to the first array item var checkedCode = sqCodesArr[0]; console.log(sqCodesArr); var thisItem = $('.question-item[id$="X'+qID+checkedCode+'"]'); $('input:hidden', thisItem).val('Y'); $('input:checkbox', thisItem).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>