Script

Feature available for users with Expert license

This article describes basic concepts related to Script survey element. Other main related articles are:

Introduction

Script element is a powerful and flexible survey programming tool. It allows to do everything that is possible with Value Assignment and much more. It supports multi-line code and all custom functions and logic, including conditionals, survey controls, own functions definition, etc.

Difference between Value Assignment and Script

Value AssignmentScript
Only 1 line codeMulti-line code
Only 1 variable assigned per elementAll variables can be assigned within one script element
Limited functions and logic supportComplete functions and logic support, including conditionals, custom functions, etc.
Only value assignmentAlso survey behavior control
Basic variable types: string, integer, real, dateAlso matrix and json variable types.

Basic concepts

1. Pre-condition: understand Value Assignment

Script and Value Assignment share the same basic concepts, including execution moment behavior, page-break creation, etc. Please read Value Assignment article first before starting to work with Scripts.

2. Add Script element to the survey

Navigate to “Add content” menu and find it in “logic and actions” section:

3. Create variable(s) and start programming

Script element allows you to flexibly create and work with any variables in your survey. See example logic below for checking current month and quarter by using one of date-related functions and IF-THEN-ELSE statements:

4. Reference complete list of available functions and logic

At the heart of Script element lives Math.js library. On top of it, we have added a number of own custom functions for survey control and advanced logic.

When working with Script element, it is useful to always reference our comprehensive list of available functions.

Basic calculations and functions

Basic calculations and functions are the same as the ones used in Value Assignment, however in Script it is possible to use them in the multi-line way.

Basic arithmetics

Assigning a calculated value to a variable, you can use the basic arithmetics:

  • Addition: +
  • Subtraction: –
  • Multiplication: *
  • Division: /

With the help of brackets ( ) the priorities of certain calculation parts can be shifted.

Automatic sum example

The respondent is asked to register the turnover for each region. The total sum should be calculated automatically.

The best question type for this task would be a matrix question (the example uses the variable name “turnover”). The matrix grid has 1 column (data input “Text” and data type “Integer number”) and 4 rows, one for each region. There is a 5th row for the total sum. Since the sum should be calculated immediately, the Script must be set to “anytime” execution. A Script with “anytime” execution can be placed anywhere.

** autosum (anytime execution)
turnover_5_1 = turnover_1_1 + turnover_2_1 + turnover_3_1 + turnover_4_1
** read only setting
setSurveyFieldsReadOnly(turnover_5_1)

In first row the name of the target variable turnover_5_1 is written down instead. Behind the equals sign the sum to calculate follows. Since the participant should not fill-in the sum by himself, the function setSurveyFieldsReadOnly() is used to set the field that corresponds to the sum variable to “read only” mode. In case the exact variable names are unknown, you can export the (filled or empty) raw data file on Analyze page and look into the code plan.

Numerical functions

Besides the basic arithmetics there are more numerical functions available. The following examples show the frequently used other numerical functions:

  • square (raise to the power of …)
  • square root
  • round to decimal
  • modulus (remainder after division by …)
** input variable
a = 5
** square and root
integer1 = a^2
real1 = sqrt(a)
** round to … decimal
real2 = round(real1,2)
** modulus (remainder after division by …)
integer2 = a%2

The calculated variable values (shown in a textblock) look like this:

Furthermore, there are numerical functions that process more than one variable, e.g. random selection or statistical calculations. The following examples show:

  • randomization and random number
  • arithmetic mean
  • arithmetic mean recognizing N/A answers and missings
** input variables
a1 = 2
a2 = 3
a3 = 5
a4 = null
min = 2
max = 5
** randomization and random number
integer3 = pickRandom([a1,a2,a3])
integer4 = randomInt(min,max)
** arithmetic mean
real3 = mean(a1,a2,a3)
** arithmetic mean recognizing N/A answers and missings
real3 = meanValid("a1,a2,a3")

Using the function pickRandom() the first element of the randomized variable list is returned. The random number that is created with the function randomInt() is a randomly chosen integer number between a minimum and a maximum value (minimum value included and maximum value excluded). The function mean() is one example of typical statistical calculations. In case there are missings within the answers, you need to use meanValid() function to filter them out. The calculated values (shown in a textblock) look like this:

String functions

Script can also be used to transform string content. The most important string functions are:

  • concatenation
  • substring verification
  • text comparison
** input variables
postalcode = "CH-8005"
town = "Zürich"
** concatenation
text1 = concat(postalcode," ",town)
** substring verification
text2 = postalcode[4:7]
integer1 = indexOf(postalcode,"8005")
integer2 = indexOf(postalcode,"5008")
** text comparison
boolean1 = equals(town,"Zürich")
boolean2 = equals(town,"Utrecht")

The variable values from the examples (shown in a textblock) look like this:

To concatenate texts you have to put the texts/variables comma separated into the function concat().

To extract a substring starting and ending at certain positions the start and end positions have to be written down separated by a colon into square brackets that follow the string variable. If you are looking for a specific substring, use the indexOf() function and write down the text variable and the substring you are looking for inside brackets.

Attention, the very first character has position 0. If the searched substring does not occur, the result is -1. The last example shows one successful and one failed text comparison. The result is either “true” or “false” (in each interview language, the English expressions are returned).

The text comparison, as shown in the example above, is the only way to create a filter condition that checks the exact match of the contents of two text variables.

Date functions

Scripts can be used for dates that are to be checked during the current interview to verify whether they are within a certain time span, are before or after a fixed date or do not exceed a maximum deviation from the current date. To do this, the date is converted into a date timestamp, which is nothing more than a consecutive number that starts with 0 at a fixed point in time in the past and progresses practically to infinity. Each date has a distinctive timestamp. The difference between the time stamps of two consecutive days is always identical.

The date2number() function determines the timestamp of the specified date (at 0 o’clock UTC) to the nearest millisecond. A day has 86 400 000 milliseconds, so the timestamp divided by 86 400 000 indicates the number of days since the start time in the past. If one wants to compare a specified date with the current day of the interview, then one can determine the timestamp of the interview date using the function today() and then work out the difference. In the Script it would look like this:

** date timestamp of participant answer stored in variable "date"
integer1 = date2number(date)/86400000
** date timestamp of today
integer2 = date2number(today())/86400000
** difference (number of days) between participant answer and today
integer3 = integer1 - integer2

Complex functions

For complex use cases or for scientific use, various advanced functions are available. Some of them are listed below. Scripts use the Math.js library. As such, the Math.js online documentation can be consulted for further information. For customers without an SLA (Service Level Agreement), there is no further support related to these complex functions.

Next button and Back button functions

To control the behaviour of the Next button and the Back button, the following functions are available:

  • Display the Next button only after a specified number of seconds
  • Automatically click the Next button after a specified number of seconds
  • Hide the Next button and automatically click it after a specified number of seconds
  • Hide the Back button
** hide next button for 5 seconds
NextButton("hide",5)
** click next button automatically after 5 seconds
NextButton("click",5)
** hide next button and click automatically after 5 seconds
NextButton("hideandclick",5)
** hide back button
BackButton("hide")

The buttons will always appear at the end of a page. A Script always creates a page break immediately before it. Therefore, the Script with the button functions must be positioned at the beginning of the required page. If there are any other Scripts at this location in the survey, they must be inserted before the Script with the button functions. The default option “every time” should be selected as the execution option.

Convert data types

In some situations, the data are stored in variables whose data type restricts further processing of the data and therefore requires a conversion of the data type. Usually these are numbers that are stored in a text variable. Or the other way round, one would like to have numbers (e.g. year numbers) formatted in a fixed way without automatic thousand separators, so that they should be stored in a text variable. The following are the most important functions for converting data types:

** conversion string to integer number
integer1 = parseNumber("12345")
** conversion string to real number
real1 = parseReal("12345.67")
** conversion real or integer number to string
text1 = convertToString(12345.670)

Viewing the contents of the new variable (displayed in a text block) shows the numbers that were previously stored as text with number layouts (thousands and decimal separators as well as exactly 3 decimal places for fractions/real numbers). The former fractional/real number, which is now in a text variable, has no number layout and the last 0 (3rd decimal place) was automatically removed:

If-Then-Else function

If you want to define a variable in a different way depending on the contents of another variable, you can use the If-Then-Else function. This function uses a special syntax which must be followed exactly:

If-condition ? Then-statement : Else-statement

The colon (introduction to the Else-statement) is mandatory. It must always be followed by a statement which, for example, may also be variableXY=variableXY and which does not trigger any action. If an as-is comparison of variables and values occurs in the If-condition, a double equal sign must be used. The single equal sign is always an assignment, never a comparison. And if you nest several If-Then-Else functions inside each other because there are more than just 2 different expressions, then the above syntax must be followed meticulously at each level of nesting. It is recommended to work with brackets for convenience, but they are not obligatory.

** basic if-then-else clause example
integer1==2 ? integer2=5 : integer2=integer2
** nested if-then-else clause example
integer1==2 ? integer2=5 : (integer1==3 ? integer2=7 : integer2=11)

Answer counter

Using certain functions, the answers of all previous participants in the survey can be counted in Script and be made available in the interview. On the one hand, there are functions that count all interviews in the respective status (example 1). On the other hand, there is a function which allows you to define the counting condition yourself (example 2).

Example 1 shows the functions for counting all finished and all started interviews of this survey. The participant’s interview belongs to the started interviews at the moment of counting. If the interview has been finished, it changes to the completed interviews.

** get the total of all started or completed interviews
counter1 = survey.count_started
counter2 = survey.count_completed

The situation for example 2 is as follows. An event is offered repeatedly at different times, so that every participant who wants to register can freely choose his or her date. However, the capacities are limited. If a date is fully booked, it must be hidden from the selection. To do this, you need information as regards the number of registrations for each single date. The date selection is carried out via a single choice question with the variable name “eventtime”. Only completed interviews are counted. This is how the Script would look like:

** get the total of each answer (only completed interviews)
counter1 = countInterviews(eventtime==1 and survey.State=='Completed')
counter2 = countInterviews(eventtime==2 and survey.State=='Completed')
counter3 = countInterviews(eventtime==3 and survey.State=='Completed')
counter4 = countInterviews(eventtime==4 and survey.State=='Completed')

The countInterviews() function can generally contain any filter condition. If several variables are used, they can be linked with “and” or “or”. The same priority rules apply as with the element filters. If the interview status is to be part of the filter condition, the descriptions must be selected that are also found in the raw data export under “Status” (no difference in various interview languages).

Important: If a Data Cube is enabled for the survey, counter functions such as countInterviews(), count_started and count_completed use the data currently synchronized to the Data Cube. They therefore do not represent live interview counts between cube refreshes and should not be used for logic that depends on real-time counts.

Matrix and JSON data types

When you create a custom variable, you can select “Matrix” and “JSON” as a data type. These are two special data types for specific functions which can be explained in detail in a chargeable training course. Below is an example of how to fill a matrix and a JSON variable:

** matrix with 2 rows and 3 columns
matrix1 = [[1,-3,2],[1,2,7]]
** json with typical tree structure
json1 = toJSON({"tree":[{"branch1":[{"name":"new","leaves":12}]},{"branch2":[{"name":"old","leaves":null}]}]})
** access values of a matrix
a = matrix1[ROW-ID,COLUMN-ID]

A matrix can be used to perform the usual calculations such as addition and multiplication. A JSON variable can be used as an extensive list (e.g. postal codes and corresponding city names) that can be accessed from the survey.

Tips & Tricks

Code commenting

Script code can be commented using one of the following syntax:

** example comment 1
q1 = 1
# example comment 2
q2 = 2

Using Big Editor

You can edit Script code in a dedicated “big editor” pop-up, making it easier to work with longer or more complex code – just click Open big editor button.

Updated on August 26, 2026
Was this article helpful?

Related Articles