Welcome to the LimeSurvey Community Forum

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

Custom javascript Question Data not being populated in exported CSV file

  • bhavik
  • bhavik's Avatar Topic Author
  • Offline
  • New Member
  • New Member
More
5 months 1 week ago #252303 by bhavik
Please help us help you and fill where relevant:
Your LimeSurvey version: Latest
Own server or LimeSurvey hosting:  dev.smartresearchadvisor.com/limesurvey/index.php/admin/index
Survey theme/template: Custom Bootswacth
==================
I am using a customized Array Text question to have three radio buttons. I have attached the file below. When I am testing the results by exporting CSV files the data for this question along with others are not being populated in the CSV or Excel files. I have used this same script in another question and it is working fine.

Please Log in to join the conversation.

  • tpartner
  • tpartner's Avatar
  • Offline
  • LimeSurvey Community Team
  • LimeSurvey Community Team
More
5 months 1 week ago #252317 by tpartner
None of the volunteers here want to waste time guessing at the language, create a survey and import a .lsq file.

Always attach a survey export (.ls file) containing only the relevant questions.

Also provide the code used.

Cheers,
Tony Partner

Solutions, code and workarounds presented in these forums are given without any warranty, implied or otherwise.
The following user(s) said Thank You: DenisChenu

Please Log in to join the conversation.

  • bhavik
  • bhavik's Avatar Topic Author
  • Offline
  • New Member
  • New Member
More
5 months 1 week ago #252349 by bhavik
Here is the script:

<script type="text/javascript" src=" code.jquery.com/jquery-3.6.0.min.js ">
<script type="text/javascript">
    $(document).ready(function() {
        var checkClosest = function(event) {
            event.target.firstElementChild.click();
        };

        var thisQuestion = $('#question{QID}');

        // Insert dropdowns
        if (!thisQuestion.find(".inserted-dropdown").length) {
            var dropdownTemplate = '<div style="text-align: left" class="list-question-select">\
                <span class="clickable-span">\
                    <select class="inserted-dropdown" name="dropdown_{QID}">\
                        <option value="">Please choose</option>\
                        <option value="rare, not severe">rare, not severe</option>\
                        <option value="rare, severe">rare, severe</option>\
                        <option value="occasional, not severe">occasional, not severe</option>\
                        <option value="occasional, severe">occasional, severe</option>\
                        <option value="frequent, not severe">frequent, not severe</option>\
                        <option value="frequent, severe">frequent, severe</option>\
                        <option value="No">Not Applicable</option>\
                    </select>\
                </span>\
            </div>';
            
            $('.answer-item', thisQuestion).addClass('with-select').each(function() {
                var dropdownHtml = dropdownTemplate.replace(/{QID}/g, $(this).data('qid'));
                $(this).append(dropdownHtml);
            });
        }
        
        // Insert date fields with "Know" and "Don't know" options
        if (!thisQuestion.find(".date-fields").length) {
            var dateFieldsTemplate = '<div class="date-fields" style="display: none;">\
                <div class="date-field-container">\
                    <label>Approx date of onset (if known):</label><br>\
                    <label class="know-label">Know:</label>\
                    <input type="date" class="date-field large-date" id="onset-date_{QID}">\
                    <br>\
                    <label class="dont-know-label">Don\'t know:</label>\
                    <input type="checkbox" class="dont-know-checkbox" id="dont-know-onset-date_{QID}">\
                </div>\
                <div class="date-field-container">\
                    <label>Approx end date (if at all):</label><br>\
                    <label class="know-label">Know:</label>\
                    <input type="date" class="date-field large-date" id="end-date_{QID}">\
                    <br>\
                    <label class="dont-know-label">Don\'t know:</label>\
                    <input type="checkbox" class="dont-know-checkbox" id="dont-know-end-date_{QID}">\
                </div>\
                <div class="inline-fields">\
                    <textarea class="comment-box" rows="3" cols="40" style="width: 100%;" placeholder="Comments"></textarea>\
                </div>\
            </div>';
            
            $('.answer-item', thisQuestion).each(function() {
                var dateFieldsHtml = dateFieldsTemplate.replace(/{QID}/g, $(this).data('qid'));
                $(this).append(dateFieldsHtml);
            });
        }

        thisQuestion.find("select[name^='dropdown']").each(function() {
            var currName = $(this).attr('name').substr(8);
            var listQuestionSelect = $(this).closest(".answer-item").find(".list-question-select");
            var dateFields = $(this).closest(".answer-item").find(".date-fields");
            
            listQuestionSelect.find('select').each(function() {
                $(this).attr('name', 'dropdown' + currName);
            });
            
            listQuestionSelect.find('select.inserted-dropdown').on("change", function(event) {
                var answerItem = $(this).closest('.answer-item');
                var selectedValue = $(this).val();
                var dateFields = answerItem.find('.date-fields');
                
                if (selectedValue !== '' && selectedValue !== 'No') {
                    dateFields.show();
                } else {
                    dateFields.hide();
                }
            });

            listQuestionSelect.find('.comment-box').on('click', function(event) {
                event.stopPropagation();
                
            });
        });
        


        // Clean-up styles
        $('select.inserted-dropdown').addClass('big-dropdown');
        $('.list-question-select span').addClass('clickable-span');
        $('.with-select input:text', thisQuestion).css({
            'position': 'absolute',
            'left': '-9999em'
        });
        
        // Hide all rows in the array text question initially
        $('[id^="javatbd128651X28X6425SQ"]').hide();
        //$('.ls-heading.ls-header .answertext.control-label[role="columnheader"]').hide(); // Hides the headers
        //$('.ls-heading.ls-heading-repeat').hide();
        $('#question6425').hide();
        
        $('[id^="answer128651X28X6347SQ"]').change(function() {
            // Extract the subquestion code from the checkbox ID
            var row = this.id.match(/SQ\d+$/)[0];
            console.log('row:', row);
        });
        
        var checkedQuestionCodes = []; // Initialize an empty array to store checked question codes
        // Event handler for radio button changes
        $('input.inserted-radio[type=radio]').change(function() {
            // Extract the last part of the name attribute which is the subQuestionCode
            var subQuestionCode = $(this).attr('name').split('_').pop();
            console.log('SubQuestionCode:', subQuestionCode);
            
            var name = $(this).attr('name');
            var sqIndex = name.indexOf('SQ'); // Find the index of 'SQ' in the string
            var questionCode = sqIndex !== -1 ? name.substring(sqIndex, sqIndex + 5) : null; // Extract 'SQ' and the following three characters
            
            // Check if the selected radio button's value is "1"
            if ($(this).val() === "1") {
                if (checkedQuestionCodes.indexOf(questionCode) === -1) {
                    checkedQuestionCodes.push('#javatbd128651X28X6425' + questionCode);
                }
                $('#javatbd128651X28X6425' + questionCode).show();
                $('.ls-heading.ls-header .answertext.control-label[role="columnheader"]').show();
                $('#question6425').show();
            } else {
                var index = checkedQuestionCodes.indexOf('#javatbd128651X28X6425' + questionCode);
                if (index !== -1) {
                    checkedQuestionCodes.splice(index, 1);
                }
                $('#javatbd128651X28X6425' + questionCode).hide();
            }
            console.log('Checked Question Codes:', checkedQuestionCodes);
        });
        $('input.inserted-radio[type=radio][value="1"]:checked').each(function() {
            $(this).trigger('change');
        });
        

        
    });
</script>
<style>
    .know-label,
    .dont-know-label {
        text-indent: 10px;
    }
    .ls-heading.ls-header .answertext.control-label[role="columnheader"] {
        background-color: #add8e6; /* Light blue color */
    }
</style>
 

Please Log in to join the conversation.

  • Joffm
  • Joffm's Avatar
  • Offline
  • LimeSurvey Community Team
  • LimeSurvey Community Team
More
5 months 1 week ago #252351 by Joffm
As tpartner wrote

Always attach a survey export (.lss file) containing only the relevant questions.
 


Volunteers are not paid.
Not because they are worthless, but because they are priceless

Please Log in to join the conversation.

  • bhavik
  • bhavik's Avatar Topic Author
  • Offline
  • New Member
  • New Member
More
5 months 1 week ago #252352 by bhavik
Here is the LSS file with the relevant question:

Please Log in to join the conversation.

  • bhavik
  • bhavik's Avatar Topic Author
  • Offline
  • New Member
  • New Member
More
5 months 1 week ago #252353 by bhavik
Here is the LSS File

Please Log in to join the conversation.

  • tpartner
  • tpartner's Avatar
  • Offline
  • LimeSurvey Community Team
  • LimeSurvey Community Team
More
5 months 1 week ago #252362 by tpartner
A few problems,

- You don't need to load jQuery in your scripts - it is already loaded.
- There are some undefined variables in the script in the first question.
- The script in the second question is has several errors.

This script, placed in the source of an array-texts question will hide the text inputs and insert radio inputs to control them.

Code:
<script type="text/javascript" data-author="Tony Partner">
 
  $(document).on('ready pjax:scriptcomplete',function(){
    var thisQuestion = $('#question{QID}');
 
    // If inserted radios not present
    if ($('.inserted-radio', thisQuestion).length == 0) {
 
      // Define the radio list HTML
      var radioTemplate = '<ul class="list-unstyled radio-list">\
        <li class="answer-item radio-item">\
          <input type="radio" class="inserted-radio" value="1" name="SGQA" id="inserted-radio-SGQA-1">\
          <label for="inserted-radio-SGQA-1" class="control-label radio-label">Yes</label>\
        </li>\
        <li class="answer-item radio-item">\
          <input type="radio" class="inserted-radio" value="2" name="SGQA" id="inserted-radio-SGQA-2">\
          <label for="inserted-radio-SGQA-2" class="control-label radio-label">No</label>\
        </li>\
        <li class="answer-item radio-item">\
          <input type="radio" class="inserted-radio" value="3" name="SGQA" id="inserted-radio-SGQA-3">\
          <label for="inserted-radio-SGQA-3" class="control-label radio-label">??</label>\
        </li>\
      </ul>';
 
      // Insert the radios
      $('.answer-item', thisQuestion).addClass('with-radios').each(function() {
        var thisSQID = $(':text.form-control', this).attr('id').replace(/answer/, '');        
        var radioHtml = radioTemplate.replace(/SGQA/g, thisSQID);
        $(this).append(radioHtml);
      });
    }
 
    // Listener on the radios
    $('.radio-item :radio', thisQuestion).on('click', function() {
      $(this).closest('td').find(':text.form-control').val($(this).val()).trigger('keyup');
    });
 
    // Returning to the page
    $(':text.form-control', thisQuestion).filter(function() {
      return $.trim($(this).val()) != '';
    }).each(function() {
      var thisCell = $(this).closest('td');
      var thisVal = $.trim($(this).val());
      $('.inserted-radio[value="'+thisVal+'"]', thisCell).trigger('click');
    });
 
    // Apply some styles
    $(':text.form-control', thisQuestion).css({
      'position': 'absolute',
      'left': '-9999em'
    });
    $('.radio-list', thisQuestion).css({
      'text-align': 'left'
    });
  });
</script>

Cheers,
Tony Partner

Solutions, code and workarounds presented in these forums are given without any warranty, implied or otherwise.

Please Log in to join the conversation.

Lime-years ahead

Online-surveys for every purse and purpose