Quantcast
Channel: Topics in Category: Can I do this with LimeSurvey? - LimeSurvey forums
Viewing all articles
Browse latest Browse all 17529

JS for selecting two random responses from a multiple choice question - by: tpartner

$
0
0
Instead of the short-text question, I would insert a multiple-short-text with 2 subquestions and shuffle the array something like this:

<script type="text/javascript" charset="utf-8">
	$(document).ready(function() {
 
		// Identify the questions
		var thisQuestion = $('#question{QID}');
		var qHidden = thisQuestion.nextAll('.multiple-short-txt:eq(0)');
		var hiddenInput1 = $('input.text:eq(0)', qHidden);
		var hiddenInput2 = $('input.text:eq(1)', qHidden);
 
		// Hide qHidden
		qHidden.hide();
 
		// Class for "Other
		$('input.text', thisQuestion).closest('.answer-item').addClass('other-item');
 
		// Listener on the checkboxes
		$('input.checkbox', thisQuestion).on('change', function(e) {
			handleChecked();
		});
 
		// Listener on the "Other" input
		$('input.text', thisQuestion).on('keyup change', function(e) {
			setTimeout(function() {
				handleChecked();
			}, 250);
		});
 
		function handleChecked() {
			// Build an array of checked answers
			var checkedAnswers = [];
			$('input.checkbox:checked', thisQuestion).each(function(i) {
				if($(this).closest('.answer-item').hasClass('other-item')) {
					checkedAnswers.push($(this).closest('.answer-item').find('input.text').val());
				}
				else {
					checkedAnswers.push($.trim($(this).nextAll('.label-text:eq(0)').text()));
				}
			});
 
			// Shuffle the array
			shuffleArray(checkedAnswers);
 
			// Load the hidden question with a random 2 items from the array
			$(hiddenInput1).val(checkedAnswers[0]);
			if(checkedAnswers.length > 1) {
				$(hiddenInput2).val(checkedAnswers[1]);
			}
			else {
				$(hiddenInput2).val('');
			}
 
			// Fire Expression Manager
			checkconditions(hiddenInput1.value, hiddenInput1.name, hiddenInput1.type);
			checkconditions(hiddenInput2.value, hiddenInput2.name, hiddenInput2.type);
		}
    });
 
	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:

File Attachment:

File Name: limesurvey_survey_264794.lss
File Size: 20 KB

Viewing all articles
Browse latest Browse all 17529

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>