Javascript Toolkit Code Snippets

Here are some snippets of JavaScript code you can use when using wscScripting to interact with questions on the page.
Reference Guide

Randomise an Array

This is a very common activity. You might need to adjust the order of some choices or other data you are manipulating.
var aData = [1, 2, 3, 4, 5, 6];
wscScripting.randomizeArray(aData);

// E.g [3, 2, 5, 4, 6, 1]
This will randomly sort the the data in the array. The data held in aData will be randomised

Sort an Array of Numerics

You might need to adjust the order of some numbers to ensure the numbers selected are in ascending or descending order
var aData = [10, 2, 7, 5, 1, 4];
wscScripting.sortNumericArray(aData, true);

// E.g [1, 2, 4, 5, 7, 10]
This will sort the the data in the array. The data held in aData will be sorted. Changing the 2nd parameter to false will sort the array in descending order.

Sort an Array of Strings

You might need to adjust the order of some pieces of text to ensure the text selected are in ascending or descending order
var aData = ['Ten', 'Two', 'Seven', 'Five', 'One', 'Four'];
wscScripting.sortStringArray(aData, true);

// E.g ['Five', 'Four', 'One', 'Seven', 'Ten', 'Two']
This will sort the the data in the array. The data held in aData will be sorted. Changing the 2nd parameter to false will sort the array in descending order.

Get First Ranked Choice in a Ranking Question

You might need to find which choice was selected first
// Assumes there is a Question with a Data Access Code of 'SOURCE'
var oQuestion = wscScripting.getQuestionByDataPipingCode('SOURCE');
var aRanks = wscScripting.getSelectedRanks(oQuestion);
if (aRanks && aRanks.length > 0) {
    var oChoice = aRanks[0];
    // e.g. Choice Text is oChoice.text
}
This will obtain the question and then query the choices that may have been ranked. Once done, you can then look at the top selected choice.

Select choices in a Question based on selections in a previous Question based on their value

This is a very common activity. You have a question where you have some choices selected and wish to select similar choices in a subsequent question. You might do this to aggregate selections from multiple questions.
// Assumes there are 2 Questions with a Data Access Codes of 'SOURCE' and 'TARGET'
// Both questions have choices with the same values

var oSource = wscScripting.getQuestionByDataPipingCode('SOURCE');
var oTarget = wscScripting.getQuestionByDataPipingCode('TARGET');
if (oSource && oTarget) {
    var aSelected = wscScripting.getSelectedChoices(oSource);
    if (aSelected.length > 0) {
        for (var nChoice = 0;nChoice < aSelected.length;nChoice++) {
            wscScripting.selectChoiceByValue(oTarget, aSelected[nChoice].value);
        }
    }
}
This will obtain the selected choices for the SOURCE question and then select the choice in the TARGET question based on the same value.

Select choices in a Question based on selections in a previous Question based on a TAG called CODE

Sometimes you might have a question where you have some choices selected and wish to select similar choices in a subsequent question. If both questions do not have the same choice values you'll need to use TAGS to find the right choice to select.
// Assumes there are 2 Questions with a Data Access Codes of 'SOURCE' and 'TARGET'
// Both questions have choices which use TAGS with a TAG name of CODE

var oSource = wscScripting.getQuestionByDataPipingCode('SOURCE');
var oTarget = wscScripting.getQuestionByDataPipingCode('TARGET');
if (oSource && oTarget) {
    var aSelected = wscScripting.getSelectedChoices(oSource);
    if (aSelected.length > 0) {
        for (var nChoice = 0;nChoice < aSelected.length;nChoice++) {
            var oChoice = aSelected[nChoice];
            var oTag = wscScripting.getTagValueByName(oChoice.tags,'CODE');
            if (oTag) {
                var oTargetChoice = wscScripting.getChoiceByTagValue(oTarget, 'CODE', oTag.text);
                if (oTargetChoice) {
                    wscScripting.selectChoice(oTarget, oTargetChoice);
                }
            }
        }
    }
}
This will obtain the selected choices for the SOURCE question and then select the choice in the TARGET question based on the choices in both questions having the same TAG values for the TAG called CODE

Create a custom validation and validation message

Sometimes you might have a need to validate a question based on very specific criteria. This could include specific business logic. For example, checking postal codes.

This script shows validating a Text Question for specific values. The principal can then be applied to any question.

This script should be placed in the Execute Javascript before Survey Page is Validated scripting event.
// Assumes a Text Question with a Data Access Code of 'SOURCE'
var oQuestion = wscScripting.getQuestionByDataPipingCode('SOURCE');
if (oQuestion) {
    var sValue = wscScripting.getValue(oQuestion);
    // Test the value here
    // For example ensure the value entered is 'ONE' or 'TWO'
    if (sValue == 'ONE' || sValue == 'TWO') {
        // This value is valid
        wscScripting.clearValidation(oQuestion);
        args.isValid = true;
    }
    else {
        // This value is not valid
        wscScripting.setValidation(oQuestion, 'You must enter a valid value');
        args.isValid = false;
    }
}
This will check the value from the question and compare it to valid values. If it succeeds, it clears any validations that might exist. If it doesn't succeed, it sets a validation message for the question.

The message will appear similar to other validation messages for questions.
Validation Message

Get a Url Parameter. That is, a Query String

Sometimes you might have a link to a survey and have additional parameters passed. For example, this can happen when you use Panel Providers. To get access to these parameters in script you can utilise the getUrlParameter function.
var sParameter = wscScripting.getUrlParameter('lang');

// E.g sParameter == 'en'
This will obtain a language code passed into the survey.

Load Custom CSS

Sometimes you might have a need to use custom style sheets (CSS) to maintain a client's corporate style for their survey.

You can use Themes to load custom external CSS or you could might want to load it via JavaScript
$('head').append(
        $('<link rel="stylesheet" type="text/css" />')         .attr('href','https://fonts.googleapis.com/css?family=Lobster&subset=latin,latin-ext') );
This will load a font from the Google Font API and make it available in your markup.

Select Choices based on "Least Filled" Quotas

Sometimes you need to have your survey react in very specific ways to Quotas so that different pathways can be taken based on how many quotas have been filled.

You can use scripting to review the Quotas and then select choices or undertake other actions. Selecting choices might allow additional Quotas to be calculated or Flow Control to operate based on current Quota calculations.

This script finds the "Least Filled" Quotas and then based on the Quota Codes selects choices in a Choice question.
var nNumberToSelect = 3;
var oQuestion = wscScripting.getQuestionByDataPipingCode('QUOTACHOICES');

// Get the quotas
var aQuotas = new Array();
aQuotas.push(wscScripting.getQuotaByCode('QUOTA1'));
aQuotas.push(wscScripting.getQuotaByCode('QUOTA2'));
aQuotas.push(wscScripting.getQuotaByCode('QUOTA3'));
aQuotas.push(wscScripting.getQuotaByCode('QUOTA4'));
aQuotas.push(wscScripting.getQuotaByCode('QUOTA5'));

// Shuffle the quotas first
wscScripting.randomizeArray(aQuotas);

// Sort the list to be in least responded order
aQuotas.sort(function(a,b) {
    return a.numberResponded - b.numberResponded
});

// Select choices while we have least filled to a maximum of nNumberToSelect
for(var nQuota = 0;nQuota < aQuotas.length;nQuota++) {
    var oQuota = aQuotas[nQuota];
    if (wscScripting.getSelectedChoices(oQuestion).length >= nNumberToSelect) {
        // Do not select any further
        break;
    }
    // Find a choice that has a code that matches the quota code and select it
    var oChoice = wscScripting.getChoiceByTagValue(oQuestion, 'CODE', oQuota.code);
    if (oChoice) {
        wscScripting.selectChoice(oQuestion, oChoice);
    }
}
This will pick the least filled quotas up till a maximum limit and then select the same choices based on their TAG.

Connect to a VoxPopMe project

For those users who want to connect their survey to a VoxPopMe project you will need to follow the VoxPopMe guide for building the embedded script.

The following script is an example of how this could be achieved. The code is available as-is with no guarantee of it's ability to work with current versions of VoxPopMe.
$('#{QuestionContainer}').addClass('wsc_question-zone');
$('#{QuestionContainer}').html('<div class="wsc_question-body" id="xx"><div class="vpm-capture-widget"></div></div>');

vpm_widget_config = {
    project_id: "put-you-voxpopme-project-id-here",
    additional_data: {
        'first_name': 'Xxxxx',
        'userid': wscScripting.getRecallCode()
    },
    settings: {
        locale: "en-GB"
    },
    disable_next_button: function() {
        // Insert disable 'Next' button function appropriate to your survey platform here
        $('#nextbutton').hide();
        $('#submitbutton').hide();
    },
    enable_next_button: function() {
        // Insert enable 'Next' button function appropriate to your survey platform here
        $('#nextbutton').show();
        $('#submitbutton').show();
    }
};
!function(a,b,c,d){function e(){var a=b.createElement(c);a.type="text/javascript", a.async=!0,a.src=d;var e=b.getElementsByTagName(c)[0]; e.parentNode.insertBefore(a,e)}a.attachEvent?a.attachEvent("onload",e):a.addEventListener("load",e,!1)}(window,document,"script","https://capture.voxpopme.net/main.js");

    document.addEventListener("DOMContentLoaded", function(event) {

    // Replace your_NextButton below with the appropriate function
    // to disable 'Next' button in your survey platform
    document.getElementById("nextbutton").style.display = "none";

    // Replace your_checkbox is your survey platform's class for selection a checkbox
    $('.wsc_checkfield input').change(function() {
            // click checkbox?
            if ($(this).is(':checked')) {
                // Insert enable 'Next' button function appropriate
                // to your survey platform here
                $('#nextbutton').show();
            } else {
                // Insert disable 'Next' button function appropriate
                // to your survey platform here
                $('#nextbutton').hide();
            }
    });
});
args.isValid = true;
For more information on wscScripting click here to see the complete scripting guide.
We recommend utilizing a tool such as the Chrome Dev Tools which will allow you to see the script and even test javascript in your web pages.

This will make it easier to determine the right script to use and also allow you to play with the scripts to obtain the best result.

The Chrome Dev Tools are perfect when testing your Custom Themes too.