Welcome to the LimeSurvey Community Forum

Ask the community, share ideas, and connect with other LimeSurvey users!

Select random answer from previous question

More
5 years 6 months ago #173192 by ioteo
Hello,

I am looking for help on this...

I have a 'multiple short text' question where people have to write their answers (there are N short texts to write). Once this is done, I want to select randomly one of those texts to ask questions to that specific text/answer. I am wondering if there is a way to do this?

I have found how to do something similar when the question one takes the answer from is a multiple choice question:

manual.limesurvey.org/Workarounds:_Manip...estion_for_later_use

But unfortunately I am not expert in JS and don't really know how to adapt it to 'multiple short text' questions.

Is there some who could help on this? I am using LS version: 2.73.1+171220.

Many thanks in advance!

Cheers,
Iván.
The topic has been locked.
  • tpartner
  • tpartner's Avatar
  • Away
  • LimeSurvey Community Team
  • LimeSurvey Community Team
More
5 years 6 months ago - 5 years 6 months ago #173203 by tpartner
Replied by tpartner on topic Select random answer from previous question

File Attachment:

File Name: limesurvey...8-29.lss
File Size:18 KB
This script will load a hidden short-text question with a random value from the preceding multiple-short-text question. The loading is done when the page is submitted.

Code:
<script type="text/javascript" charset="utf-8">    
  $(document).ready(function() {  
 
    // Identify the questions
    var thisQuestion = $('#question{QID}');
    var qHidden = thisQuestion.nextAll('.text-short:eq(0)');
    var hiddenInput = $('input.text', qHidden);
 
    // Hide qHidden
    qHidden.hide();
 
    // Listener on submit function
    $('#limesurvey').on('submit', function(e) {
 
      // Build an array of input text strings
      var q1Answers = [];
      $('input[type="text"]', thisQuestion).each(function(i) {
        if($.trim($(this).val()) != '') {
          q1Answers.push($.trim($(this).val()));
        }      
      });
 
      // Load the hidden question with a random item from the array
      var answersLength = q1Answers.length;
      $(hiddenInput).val(q1Answers[Math.floor(Math.random()*answersLength)]).trigger('change');
    });
    });
</script>

Sample survey attached:

File Attachment:

File Name: limesurvey...8-29.lss
File Size:18 KB

Cheers,
Tony Partner

Solutions, code and workarounds presented in these forums are given without any warranty, implied or otherwise.
Last edit: 5 years 6 months ago by tpartner.
The topic has been locked.

Lime-years ahead

Online-surveys for every purse and purpose