Survey Programming Fundamentals
Survey Programming Fundamentals
d
Table of Contents
Chapter 1 Introduction to Survey Programming ..................................................................................... 1
The Big Picture ........................................................................................................................................ 1
What is Survey Design About? ............................................................................................................ 2
The Survey Process ............................................................................................................................. .... 2
Dimensions Scripting Overview ................................................................................. ............................. 2
Interview Object Model .......................................................................................................................... 2
Object Oriented Programming ............................................................................................................... 3
What is Object Oriented Programming? ............................................................................................ 3
Dimensions Development Library Overview .......................................................................................... 3
Navigating the DDL ............................................................................................................................. 4
Examples ............................................................................................................................................. 4
DDL Links ............................................................................................................................................. 5
What is mrStudio? ............................................................................................................................. ..... 6
Whats Next?........................................................................................................................................... 7
Chapter 2 Constructing Questions........................................................................................................... 9
Metadata Items Format .......................................................................................................................... 9
Information Items ................................................................................................................................. 10
Numeric Questions ............................................................................................................................. .. 11
Minimum and Maximum Parameter Options................................................................................... 12
Text Questions ...................................................................................................................................... 12
Categorical ............................................................................................................................................ 14
Parameter Options Restricting the Number of Responses to be Chosen ...................................... 14
Date....................................................................................................................................................... 17
Boolean ................................................................................................................................................. 19
Chapter 3 Creating an mrStudio Interview Script.................................................................................. 21
Opening mrStudio ................................................................................................................................. 21
Overview of Toolbars/Shortcuts ........................................................................................................... 23
Formatting Toolbars ......................................................................................................................... 23
View Toolbar ..................................................................................................................................... 24
Interview Options Toolbar ................................................................................................................ 25
I
Table of Contents Survey Programming Fundamentals
II
Survey Programming Fundamentals Table of Contents
III
Table of Contents Survey Programming Fundamentals
IV
Survey Programming Fundamentals Table of Contents
V
Table of Contents Survey Programming Fundamentals
VI
Survey Programming Fundamentals Chapter 1 Introduction to Survey Programming
This chapter
p will contain::
An overview
e of the interview process
o of Dimensions scripting
A definition
An introduction
u to documentation and
d
mrStudio
Design: Creating the survey instrument and the questions associated with it
Collect: Collect the information required of the survey instrument
Report: Analyze the results and report the findings of the research
For each stage there are different tools we can use. For Dimensions this could look like
mrStudio S
SPSS
Build AActivity Reporter
mrInterview
mrPaper mrTables
m
mrDialer
D
Author mrStudio
mrScan
mrTranslate Clementine
C
1
Chapter 1 Introduction to Survey Programming Survey Programming Fundamentals
Language Description
mrScriptBasic A programming language that is based on Microsoft VBScript.
When programming surveys we will make use of both languages. mrScriptMetadata will be used
to create the question for our survey. mrScriptBasic will control when and if we ask those
questions.
2
Survey Programming Fundamentals Chapter 1 Introduction to Survey Programming
A basic definition would read something like: A type of programming in which programmers define not
just the data type of a data structure, but also the types of operations (functions) that can be applied
to the data structure. In this way the data structure becomes an object that includes both data and
functionality.
If you have not been exposed to OOP in the past, the concepts and terminology can seem confusing at
times. However, don't get caught up in the terminology. If you understand the concept of creating a
questionnaire, then you can learn the content of this manual.
Think about OOP in terms of a survey. Specifically, let's look at a survey question as an object. A
question has question text, potential responses, as well as many other possible items. These are in fact
the data structure, what can make up part of a question. At the same time a question will require
functionality, such as asking the question or filtering the responses. These potential actions would
make up the operations that can be applied to the data structure. If this makes sense to you, then you
are on your way to grasping the concepts of OOP. (If it doesnt, this concept will make more sense as
you continue your learning.)
3
Chapter 1 Introduction to Survey Programming Survey Programming Fundamentals
You can access the DDL through the Help Contents menu choice in mrStudio, or through:
Tab Description
Contents All the DDL topics arranged in a table of contents. You can use this view like looking
through a book. It is also helpful for identifying topics related to a page you are
currently reading.
Index The index is an alphabetical list of keyword contained in the DDL. Use this view
when you know the keyword and want to quickly find topics related to it.
Search A fulltext search of the DDL. You can search on a single word, combination of
words and phrases.
Favorites Create a list of topics you have found valuable.
All the Dimensions product documentation is contained in the DDL, so finding specific topics
is a skill in itself and will take time to develop.
Examples
When you installed the DDL you also installed many examples files. The default path for these
examples is:
These example projects will prove very valuable to give you new ideas for programming.
4
Survey Programming Fundamentals Chapter 1 Introduction to Survey Programming
DDL Links
Throughout these materials you will see links pointing you to the DDL for additional information on a
topic. These are jump links and will look like:
For more information on the Interview object model, see the DDL diagram:
IOMLib.chm::/interview_Object_Model.html
5
Chapter 1 Introduction to Survey Programming Survey Programming Fundamentals
Enter (or copy and paste) the link into the Jump to this URL: textbox. Then click OK.
This will take you to the page requested. You can also do the reverse, and copy the current URL shown
above and share with others.
What is mrStudio?
mrStudio is a desktop program that assists programmers with creating scripts. Its core component is an
integrated development environment (IDE) that allows you to create, edit, run and debug Dimensions
scripts.
For survey programmers, one of the big strengths is the ability to run surveys directly inside mrStudio,
without the need for a server. You can create, test and debug a survey directly on your machine.
6
Survey Programming Fundamentals Chapter 1 Introduction to Survey Programming
Since you will be using mrStudio throughout this course, lets start with a brief overview of the
toolbars:
Toolbar Description
File: Used to create, open, save and print files.
Edit: Cut, copy, paste, undo and redo, find.
View: Controls which tabs are showing in
mrStudio.
Debug: Used to start, stop, pause and move
through a script.
Formatting: Indentations, commenting,
macros and options.
Workspace: Create and manage workspaces.
You will get to see many features of mrStudio as you move through this training.
Whats Next?
So now you have been introduced to Dimensions Scripting, object oriented programming, the
Dimensions Development Library, and mrStudio. This manual will focus on using mrStudio to create
surveys for data collection with mrInterview. We will start with basic questions and quickly move into
advanced concepts to help you create more complex surveys.
7
Chapter 1 Introduction to Survey Programming Survey Programming Fundamentals
8
Survey Programming Fundamentals Chapter 2 Constructing Questions
In this chapter we
w will:
a questionss
Create basic
m
Create a metadata filee in mrStudio
Item Description
Name Unique identifier for the ite m within your questionnaire. They must start with a
letter or underscore
c ( _ ) and contain only alphanumeric characterss or the
sy mbols @, $, #, or _
"Text" Text associated with the item (considered the label in the object model).
Type Identifies the item for its functionality
c (categorical
t questions, text only items,
etc.)
Parameters These are optional and vary by item type. An example would be the responses
to question.
Semicol on Between each item in the m etadata section o there is a semicolon.
9
Chapter 2 Constructing Questions Survey Programming Fundamentals
Information Items
To create an opening page with an introduction or have a page with graphics or opening text without
questions, you need to create an information item. The syntax is as follows:
Item Description
Name Unique identifier for the ite m within your questionnaire. They must start with a
letter or underscore
c ( _ ) and contain only alphanumeric characterss or the
sy mbols @, $, #, or _
"Text" Text associated with the item (considered the label in the object model).
info Keyword to create a textonlyy item. This is the default type if it is not
o specified.
Semicolon Between each item in the metadata section there is a semicolon.
Intro "Please participate in our research about travel. Your answers will help us to better
Example understand the travel needs of consumers."
info;
10
Survey Programming Fundamentals Chapter 2 Constructing Questions
Numeric Questions
To collect numeric data from your respondents, use one of the following item types:
Item Description
Name Unique identifier for the item within your questionnaire. They must start with a
letter or underscore ( _ ) and contain only alphanumeric characters or the
symbols @, $, #, or _.
"Text" Text associated with the item (considered the label in the object model).
long Wholenumbers only (no decimals). The range is from 2,147,483,648 to
2,147,483,647.
double Decimal numbers. 64bit floating point number with at least 15 digits of
precision, in the range 1.79769313486232E308 to 4.94065645841247E324 for
negative values; 4.94065645841247E324 to 1.79769313486232E308 for
positive.
[Min..Max] Optional parameters. Controls the minimum and maximum values the
respondent can enter. Automatically issues an error message if the amount
entered is below the minimum or above the maximum.
The following example will display boxes for the respondent to fill in with a numeric response.
DaysTravelYr "On average how many days per year do you travel for business or leisure?"
Example
long [0 .. 365];
AmtSpentAccom "What price did you pay for your last overnight accommodations?"
double [0 .. 3999.99];
11
Chapter 2 Constructing Questions Survey Programming Fundamentals
The browser will display a box and the respondent can fill in amounts of their choice, as shown below:
Item Description
[1..] Minimum amount without specifying a maximum
[..] No minimums or maximums (will allow negative numbers)
[1..100,^50] Number after ^ symbol are excluded from the range.
[1,3,5] Commas denote single values or breaking ranges.
[1..10,50..100]
Text Questions
When you want to create a question that collects any type of text information, use a text type.
Item Description
Name Unique identifier for the item within your questionnaire. They must start with a
letter or underscore ( _ ) and contain only alphanumeric characters or the
symbols @, $, #, or _
"Text" Text associated with the item (considered the label in the object model).
text Keyword to enter any characters in the question. Allows up to 4000 characters.
[Min..Max] Optional parameters. Controls the minimum and maximum characters allowed
for the question.
12
Survey Programming Fundamentals Chapter 2 Constructing Questions
If you state the maximum at 40 or less, you will see a line instead of a box. You also
have full control of the box size with styles, covered in the Controlling the Look of Your
Survey section.
13
Chapter 2 Constructing Questions Survey Programming Fundamentals
Categorical
To create a question which offers a list of options to choose from is considered a categorical type
question.
{ID1 "AltText1" ,
IDn "AltTextn" };
Item Description
Name Unique identifier for the item within your questionnaire. They must start with a
letter or underscore ( _ ) and contain only alphanumeric characters or the
symbols @, $, #, or _
"Text" Text associated with the item (considered the label in the object model).
categorical Keyword to create a question with categories for response choices.
[Min..Max] Optional parameters. Controls the minimum and maximum amount of
categories that can be chosen by a respondent. Default is open to any amount
of choices. Automatically issues an error message if the number of responses
chosen is below the minimum or above the maximum.
{ } Indicates the start of the categories you wish the respondent to choose from for
the question
ID1, IDn Unique identifying name for the response. This needs to be unique per
question, not metadata file. Rules for the response names are the same as the
name of the question.
AltText1, Optional text to show the respondent instead of the name of the question. This
AltTextn will apply when the name of the question is not the same as the text you wish to
show the respondent.
Item Description
[1] When only one number is specified in the minimum/maximum parameter, it is
assumed that this number is both the Minimum AND maximum amount.
Example shown allows for a single response to be chosen for the question. Is
the same as typing [1..1]
[1..] Allows for multiple categories to be chosen (multiple response question). Not
stating a maximum amount allows ease of updating the question with additional
responses as needed.
[1..3] States the minimum amount of categories to be chosen is 1 and the maximum is
3. Useful for questions which ask for responses Answer up to X categories.
[..] No minimums or maximums (this is the default)
14
Survey Programming Fundamentals Chapter 2 Constructing Questions
Be aware that not stating a minimum number of answers will allow the respondent to move forward in
the survey without providing a response. Allowing no answer in this way provides no method to
determine if the respondent was presented this question. The data for the respondent will simply
contain a blank.
Later in the course we will learn how to allow for the respondent to not answer a question, yet
have the data store a value showing that the respondent was exposed to the question.
TravelItem "From the list below, which one item would you most want to bring with you
Example on a leisure trip?"
categorical [1..1]
Camera,
Map,
};
15
Chapter 2 Constructing Questions Survey Programming Fundamentals
Antarctica,
Africa,
Asia,
Australia,
Europe,
};
Note in the examples above, alternate labels are not required when the text you want to
display is also a legal label name.
The checkboxes indicate that more than one response can be given as stated in the syntax as [1..].
16
Survey Programming Fundamentals Chapter 2 Constructing Questions
Date
When requesting a date from the respondent, it is easier to collect a date type versus multiple long
type fields.
Item Description
Name Unique identifier for the item within your questionnaire. They must start with a
letter or underscore ( _ ) and contain only alphanumeric characters or the
symbols @, $, #, or _
"Text" Text associated with the item (considered the label in the object model).
date Keyword to enter a date and time field. Can enter dates and times or one or the
other. Takes many different date formats (See below).
["Min".."Max"] Optional parameters. Controls the minimum and maximum date range allowed
for the question. Note the addition of the double quotes around the min/max.
The format for the date is very flexible. Some (not all) of the formats taken are:
o DDMonthNameYYY (7 April 2007)
o DDShortMonthNameYYY (7 Apr 2007)
o YYYY/MM/DD (2007/04/07)
o MM/DD/YY (04/07/07)
If you leave off certain portions of the date/time field, it will make assumptions. An example
would be if you were collecting only month and year and enter April 2007, mrInterview will
record the date as April 1, 2007. If a time is not chosen, it assumes the current time.
When you run the interview you may enter times in 12hour or 24hour format; for example,
2:30pm or 14:30. If you do not specify AM or PM, it will assume a 24hour clock.
Metadata language controls the format of the date taken. An example would be trying to
enter a UK English date of dd/mm/yy when the metatdata languages do not contain English
UK, only English US. In this case, the date would be transformed to the English US version of
mm/dd/yy.
If you want more control over the date field, create a custom control, such as the example
calendar.htm in the DDL: DDL.chm::/interviewscripting_templates_custom_writing.htm.
7
Chapter 2 Constructing Questions Survey Programming Fundamentals
Example
LastTripDate "What was the date you left for your last trip?"
date;
The result of the LastTrip date question would look like this:
18
Survey Programming Fundamentals Chapter 2 Constructing Questions
Boolean
Boolean type questions record a true or false value. In web surveys, this type is an easy way to provide
a single checkbox response.
Item Description
Name Unique identifier for the item within your questionnaire. They must start with a
letter or underscore ( _ ) and contain only alphanumeric characters or the
symbols @, $, #, or _
"Text" Text associated with the item (considered the label in the object model).
boolean Keyword to create a true/false question. Creates a checkbox on web surveys.
Checking the box is a True response and leaving it empty is false.
You can add categories to a Boolean question to simulate a categorical question. Be sure
if you use this option that you will only have 2 responses, never any more.
Here is an example of a Boolean question and what it will look like in the browser:
ReceiveTravelInfo "Check here if you wish to receive an email regarding travel safety."
Example
boolean;
9
Chapter 2 Constructing Questions Survey Programming Fundamentals
20
Survey Programming Fundamentals Chapter 3 Creating an mrStudio Interview Script
This
T chapter will cover:
How to reeate an mrStudio metadata file
f
Opening mrStudio
You will find mrStudio at:
21
Chapter 3 Creating an mrStudio Interview Script Survey Programming Fundamentals
Under File New File you will see the different types of files you can create in mrStudio.
For this course we will be creating a Metadata File (.mdd). Under file name fill in a file name for your
project and choose Open. Now you are ready to start typing the code discussed in Chapter 2 into the
metadata section.
If you need help at first, Control M displays the list of question types that you can choose
one and have the structure of the question to start with. The macros can be a nice place
to start when you dont want to go back to the DDL or manual for syntax questions.
22
Survey Programming Fundamentals Chapter 3 Creating an mrStudio Interview Script
Overview of Toolbars/Shortcuts
mrStudio has many tools to help you with the creation of your script. Lets review the different
toolbars and parts of the mrStudio screen.
Formatting Toolbars
The formatting toolbars provide basic but needed editing skills in mrStudio.
Indenting left or right icons. Indenting will become a very important aspect of your script
writing in the routing section. It will help make your code easy to follow.
Comment and Uncomment Selection icons. The comments in Dimensions Scripting are
indicated by a single quote mark and will turn the commented text green. By highlighting large
blocks of text, you can comment and uncomment the sections easily with the toolbar icons
above.
The macros icon allows you to access the predefined syntax for mrStudio. You also have the
ability to add your own macros as well.
Note that you can copy macro definitions from one machine to another by copying the file
MacroDefinitions.xml from the default mrStudio directory.
3
Chapter 3 Creating an mrStudio Interview Script Survey Programming Fundamentals
View Toolbar
This toolbar controls which tabs are showing in mrStudio. Depending on what you are trying to
accomplish, you will want to show different aspects of mrStudio.
For now, lets start with two helpful aspects, Metadata Explorer and the locals pane.
Metadata Explorer
As you create your metadata, you can open the Metadata viewer to see a treeview version of your
script:
The icons shown in this viewer are used throughout all Dimensions products to represent the question
types.
24
Survey Programming Fundamentals Chapter 3 Creating an mrStudio Interview Script
Locals
As you run a survey, the locals allows you to see your responses to the questions as shown below.
In addition, the locals pane will provide extremely helpful in this course as you start to understand the
questions as objects, as you can see the different properties of the questions.
All keywords are color coded in blue. All text within double quotes is also color coded.
When troubleshooting syntax errors, look for the appropriate color coding to help you find the
problems.
Save frequently, as your metadata will be checked for syntax errors when you save.
Error messages will state the line numbers associated with it. Notice the line numbers on the
left side of your code in mrStudio to help you with this.
25
Chapter 3 Creating an mrStudio Interview Script Survey Programming Fundamentals
After saving and closing the document, mrStudio reformats your metadata into a standardized
format. The term used for this is rehydration. Be aware of this so you dont spend additional
time on proper formatting in the metadata section.
On the browser tab in mrStudio (if you cannot see the browser tab, from the menu choose View
Browser ) you will be able to see the interview as it will appear when it is activated in mrInterview.
26
Survey Programming Fundamentals Chapter 3 Creating an mrStudio Interview Script
Later in this course we will add formatting and templates to enhance the look of the
interview; these will also be viewable in the mrStudio browser window.
You can choose to answer the questions yourself, or you can choose F5 to let mrStudio automatically
answer the questions on the screen for you. (This will prove helpful later when testing surveys with
large grid questions).
The interview will complete, but if you wish to interrupt the script, click on the Stop button in the
browser window, or the Stop (square icon) in the toolbar.
As you can see, there are many features in mrStudio to help you create your interview scripts. Some
features you will use immediately, such as the local testing of surveys and the autoanswering
questions with F5. Others, such as creating macros and viewing the locals pane information will come
later in your learning.
27
Chapter 3 Creating an mrStudio Interview Script Survey Programming Fundamentals
Exercise
Open mrStudio and create a metadata file called GroceryBill.mdd. Complete the following questions
in this document, then test the survey within mrStudio.
GroceryIntro As you agreed to previously, please have your last grocery bill available for reference for
this next section of the survey.
GroceryDate Looking at your last grocery bill, what date did you go to the store?
StoreName What was the name of the store in which you shopped?
Walmart
Safeway
Kroger
Albertsons
Ahold USA
Delhaize
Publix
WinnDixie
ItemTypes Which of the following categories of groceries did you purchase on this shopping trip?
Cheese/Olive Bar
Salad Bar
Deli Items
Meat/Seafood
Produce
Canned Goods
Pasta/Grains
Generic On this particular shopping trip, did you purchase any generic brand items?
Yes
No
28
Survey Programming Fundamentals Chapter 3 Creating an mrStudio Interview Script
PurposeTrip Briefly describe the reason for your trip to the grocery store on that particular day.
AgreeContact Please check the box below if you agree to allow us to contact you later if we have
additional questions regarding your trip to the grocery store.
29
Chapter 3 Creating an mrStudio Interview Script Survey Programming Fundamentals
30
Survey Programming Fundamentals Chapter 4 Special Responses and Options
In this
t chapter we will cover:
Special keyywords to provide additional
functionality
Creating su
ubheadings o improve the
appearance of categor ical questions
{ID1 "AltText1",
31
Chapter 4 Special Responses and Options Survey Programming Fundamentals
Item Description
Name Unique identifier for the item within your questionnaire. They must start with a
letter or underscore ( _ ) and contain only alphanumeric characters or the
symbols @, $, #, or _
"Text" Text associated with the item (considered the label in the object model).
categorical Keyword to create a question with categories for response choices. Question
type must be categorical to use the exclusive keyword.
[min..max] Optional parameters. Controls the minimum and maximum amount of
categories that can be chosen by a respondent. Default is open to any amount
of choices. Automatically issues an error message if the number of responses
chosen is below the minimum or above the maximum.
{ } Indicates the start of the categories you wish the respondent to choose from
ID1, IDn Unique identifying name for the response. This needs to be unique per
question, not metadata file. Rules for the response names are the same as the
name of the question.
AltText1, Optional text to show the respondent instead of the name of the question. This
AltTextn will apply when the name of the question is not the same as the text you wish to
show the respondent.
exclusive Makes a specific response the only choice that can be chosen in a multiple
selection question. Keyword is placed after the category name and alternate
text (if present).
AirlinesFlown "In the past year, which of the following airlines have you used for travel?"
Example
categorical [1..]
American,
Delta,
United,
};
32
Survey Programming Fundamentals Chapter 4 Special Responses and Options
If the respondent tries to choose the response Never flown before and any other response, the
following error will appear:
3
Chapter 4 Special Responses and Options Survey Programming Fundamentals
{ID1 "AltText1",
ID2 "AltText2" ,
Item Description
Name Unique identifier for the item within your questionnaire. They must start with a
letter or underscore ( _ ) and contain only alphanumeric characters or the
symbols @, $, #, or _
"Text" Text associated with the item (considered the label in the object model).
categorical Keyword to create a question with categories for response choices.
{ } Indicates the start of the special response categories you wish the respondent to
choose from for the question
ID1, ID2, IDn Unique identifying name for the response. This needs to be unique per
question, not metadata file. Rules for the response names are the same as the
name of the question.
AltText1, Optional text to show the respondent instead of the name of the question. This
AltText2, will apply when the name of the question is not the same as the text you wish to
AltTextn show the respondent.
Keyword Represents one of the keywords NA (No Answer), DK (Dont Know), or REF
(Refused)
The response is automatically set to be exclusive and fixed in the position in which it was typed
when the category order is changed.
When using the CATI (Computer Aided Telephone Interviewing) option, these keywords have
shortcut keys for the ease of use for the interviewers
These responses can be identified in a systematic way, which makes it easier to reference
these question types when creating subroutines or functions.
34
Survey Programming Fundamentals Chapter 4 Special Responses and Options
Example
HotelChainStayed "Choose the hotel chains you have stayed at this past year."
categorical [1..]
InterContinental,
Cendant,
Marriott,
Accor,
Choice,
Hilton,
};
You can use the keywords as the names for the responses; however after rehydration the names will
show as a dash ().
35
Chapter 4 Special Responses and Options Survey Programming Fundamentals
codes (
);
Item Description
Name Unique identifier for the item within your questionnaire. They must start with a
letter or underscore ( _ ) and contain only alphanumeric characters or the
symbols @, $, #, or _
"Text" Text associated with the item (considered the label in the object model).
Qtype Represents the noncategorical question types of long, double, text or date.
[Min..Max] Optional parameters. Controls the minimum and maximum values that can be
chosen by a respondent.
codes Keyword to indicate you are adding special response categories to a non
categorical question.
{ } Indicates the start of the special response categories you wish the respondent to
choose from for the question
ID1, IDn Unique identifying name for the response. This needs to be unique per
question, not metadata file. Rules for the response names are the same as the
name of the question.
AltText1, Optional text to show the respondent instead of the name of the question. This
AltTextn will apply when the name of the question is not the same as the text you wish to
show the respondent.
Keyword Represents one of the keywords NA (No Answer), DK (Dont Know), or REF
(Refused). This keyword is optional.
36
Survey Programming Fundamentals Chapter 4 Special Responses and Options
AmtSpentYr "What price did you pay for your last airline flight?"
Example
double [0 .. 3999.99]
codes (
);
This code would create checkboxes below the numeric response box as shown below:
37
Chapter 4 Special Responses and Options Survey Programming Fundamentals
{ID1 "AltText1",
Item Description
Name Unique identifier for the item within your questionnaire. They must start with a
letter or underscore ( _ ) and contain only alphanumeric characters or the
symbols @, $, #, or _
"Text" Text associated with the item (considered the label in the object model).
categorical Keyword to create a question with categories for response choices.
{ } Indicates the start of the categories you wish the respondent to choose from for
the question
ID1, ID2 Unique identifying name for the response. This needs to be unique per
question, not metadata file. Rules for the response names are the same as the
name of the question.
AltText1, Optional text to show the respondent instead of the name of the question. This
AltText2 will apply when the name of the question is not the same as the text you wish to
show the respondent.
other Keyword to create a text box on the response to collect additional information.
HotelChainStayed "Choose the hotel chains you have stayed at this past year."
Example
categorical [1..]
{ InterContinental ,
Cendant,
Marriott,
Accor,
Choice,
Hilton,
38
Survey Programming Fundamentals Chapter 4 Special Responses and Options
This will create a text box to collect the specific name of any hotel chains not listed.
Subheading
You can create textonly items to describe a group of responses by creating subheadings.
39
Chapter 4 Special Responses and Options Survey Programming Fundamentals
Item Description
Name Unique identifier for the item within your questionnaire. They must start with a
letter or underscore ( _ ) and contain only alphanumeric characters or the
symbols @, $, #, or _
"Text" Text associated with the item (considered the label in the object model).
categorical Keyword to create a question with categories for response choices.
{ } Indicates the start of the subheadings and categories
Subhead1, Name for Subheading item
Subheadn
SubheadText1, Represents alternate text for the Subheadings.
SubheadTextn
ID1, ID2,IDn Unique identifying name for the response. This needs to be unique per
question, not metadata file. Rules for the response names are the same as the
name of the question.
AltText1, Optional text to show the respondent instead of the name of the question. This
AltText2, will apply when the name of the question is not the same as the text you wish to
AltTextn show the respondent.
TravelHelp "Have you used any of the following to help you with your travel
Example arrangements?"
categorical [1..]
{
TravelBooks "Travel Books"
{
LonelyPlanetBook "Lonely Planet",
Fodor "Fodor's",
Frommer "Frommer's"
},
Websites "Websites"
{
Expedia "Expedia" ,
Orbitz "Orbitz" ,
Govt "Government Websites"
}
};
40
Survey Programming Fundamentals Chapter 4 Special Responses and Options
The previous code will create the following question in the browser:
41
Chapter 4 Special Responses and Options Survey Programming Fundamentals
Exercise
Update the first exercise (GroceryBill.mdd ) with the following additions that are highlighted below:
GroceryIntro As you agreed to previously, please have your last grocery bill available for reference for
this next section of the survey.
GroceryDate Looking at your last grocery bill, what date did you go to the store?
StoreName What was the name of the store in which you shopped?
Walmart
Safeway
Kroger
Albertsons
Ahold USA
Delhaize
Publix
WinnDixie
Other (Specify)
ItemTypes Which of the following categories of groceries did you purchase on this shopping trip?
Prepared Foods
Cheese/Olive Bar
Salad Bar
Deli Items
NonPrepared Foods
Meat/Seafood
Produce
Canned Goods
Pasta/Grains
None of These
Generic On this particular shopping trip, did you purchase any generic brand items?
Yes
No
Dont Remember
42
Survey Programming Fundamentals Chapter 4 Special Responses and Options
PurposeTrip Briefly describe the reason for your trip to the grocery store on that particular day.
AgreeContact Please check the box below if you agree to allow us to contact you later if we have
additional questions regarding your trip to the grocery store.
43
Chapter 4 Special Responses and Options Survey Programming Fundamentals
44
Survey Programming Fundamentals Chapter 5 Basic Routing Logic
h
This chapter o
covers:
n
Understanding, e
adding, removing routingg
context
u questions
Changing the order of your
n
Understanding n Functions and use
Dimensions
with logic statements
Here are some of the many things the routing section allows you to do:
To access the routing section, click on the Web tab in your .mdd file as shown below:
45
Chapter 5 Basic Routing Logic Survey Programming Fundamentals
You can add additional routings to your questionnaire. This would be necessary for surveys fielded
with multiple collection methods, such as web, paper scanning, and telephone interviewing. You
would also need to add routing if you originally created your metadata using either mrInterivews Build
activity or the accessory Word Capture, as they create a paper routing that is read only.
Tools
Add Routing Context
46
Survey Programming Fundamentals Chapter 5 Basic Routing Logic
To remove a routing context, click on the tab of the context you wish to remove and choose
There is no rehydration of the routing section, so format counts. Use Tabs to indent and make
your code easy to read.
Saving does not check the routing syntax; only when you start the survey will you see the
runtime problems.
Asking Questions
All we have done so far is create metadata and run the survey to review the questions. mrStudio will
run all the questions in the metadata if there is nothing in the routing section. This is not a practical
option, as almost all scripts have some routing. Additionally, mrInterview will not run a script without
having a proper routing section. The main items in your routing are statements to ask the questions.
Name.Ask()
Item Description
Name Metadata item name
.Ask() Displays and asks the question
We will need to create .Ask() statements for each question in our survey. To quickly ask all the
questions in your metadata,
47
Chapter 5 Basic Routing Logic Survey Programming Fundamentals
By expanding the Fields folder, you can pick and choose specific questions to copy as .Ask
statements.
48
Survey Programming Fundamentals Chapter 5 Basic Routing Logic
Name.Show()
Item Description
Name Metadata item name
.Show() Displays the question and its current response in readonly format
When .Show() is used with a question, the choices are grayed out and you are only able to see the
current response for the question as shown below.
.Show() can also be used with info items; there is no difference using a .Show() or .Ask with
an info item.
49
Chapter 5 Basic Routing Logic Survey Programming Fundamentals
Conditional Statements
Now that we have asked all the questions, lets look into ways to determine if a respondent should be
asked certain questions. This is usually called routing or skip patterns. There are two conditional items
we will review to help us create the routing for our surveys.
If Then Else
Select Case
If Then Else
If then else is a conditional statement which will compare two or more statements and test the
results. If the results are true, the then actions are taken; if not, the else actions are taken. The
syntax in Dimensions scripting is:
If condition Then
Actions
End if
Additionally, you could add the options for Else if and/or Else:
If condition Then
Actions
Actions
Else
Actions
End If
50
Survey Programming Fundamentals Chapter 5 Basic Routing Logic
Now lets look at some examples of these conditional statements. To do this, we will need to
understand the syntax for some of the Actions you could use in the conditional statements. One
action to use in the routing section is testing the response to a previous question. We will look at
many ways to do this throughout the manual. For this conditional section, here is some basic
information.
Item Description
Name Represents the metadata item name
.Response.Value Property to reference the named questions current response value
Condition or Any condition to represent a possible response for the named question, or
response specify an actual response
In the next example, we have the following questions as shown in the metadata:
End Metadata
51
Chapter 5 Basic Routing Logic Survey Programming Fundamentals
The logic for the questions is, if the answer to the TravelItem question is Friend/Travel Companion,
then ask the FriendRelate question. The logic is achieved in the following routing section with the use
of an If Then statement:
Routing(Web)
Example
TravelItem.Ask()
FriendRelate.Ask()
End If
TravelItemCost.Ask()
End If
End Routing
If the question is categorical, you will need to refer to the Name of the response (not the label that is
shown to the respondent) and enclose this in curly brackets as shown in the above example.
Select Case
Select Case statements work similar to an If Then statement. Select Case statements allow you to
create conditional actions based on a question type that can only have a single value (single
categorical, numeric, Boolean).
Case Response1
Actions1
Case ResponseN
ActionsN
...
[Case Else
ActionsN]
End Select
52
Survey Programming Fundamentals Chapter 5 Basic Routing Logic
Item Description
Select Case Marks the Start and end of the select case statement
End Select
Actions1, Actions2 Represent one or more statements to be executed if the question's response
matches the response for the current Case statement.
Case Else Represents one or more statements to be executed for respondents who fail
ActionsN all the previous Case tests
The case statement can be useful when you have many responses to test since you only specify the
question name once. The following shows the previous example for an if then statement, now with
the select case syntax.
End Metadata
53
Chapter 5 Basic Routing Logic Survey Programming Fundamentals
Routing(Web)
TravelItem.Ask()
Case {FriendTravelCompanion}
FriendRelate.Ask()
Case {Camera}
TravelItemCost.Ask()
End Select
End Routing
To have mrStudio create the case statement for you, view the metadata explorer, then
choose the question in which you will be basing the select statement. Choose the questions
categories folder and rightclick to choose Copy as Select statement. You can then paste a
shell of the select statement with the questions categories as a starting point.
54
Survey Programming Fundamentals Chapter 5 Basic Routing Logic
Goto
In the examples above, we have been creating our routing based on good programming practices in
which you nest questions within conditional statements. The methods shown thus far can help make
your code easy to follow and debug. Sometimes, however, it may be helpful to skip around statements
in the routing section. The Goto keyword can allow you to do this when combined with a conditional
statement.
Goto lineLabel
lineLabel:
Item Description
Goto Keyword indicating the script should skip to the line label indicated
Linelabel Represents a line label of your choice. The naming convention for line labels follows
the pattern of all names in the metadata. These are not seen by the respondent.
: Needed to indicate this is the line label item.
As an example, suppose we asked if the respondent travels for business. Then there are a series of
questions about business travel, and a series of questions about travel for pleasure. We can use a goto
and line labels to achieve the routing necessary.
Routing(Web)
Example
TravelforBusiness.Ask()
DaysPerYrBusinessTravel.Ask()
InternationalBusiness.Ask()
PleasureSection:
TravelforPleasure.Ask()
End Routing
55
Chapter 5 Basic Routing Logic Survey Programming Fundamentals
Logical Expressions
In the previous section, we looked at some very simple logical expressions, such as
QuestionName.Response.Value = response. We will cover additional options for creating expressions.
Numeric Questions
For testing numeric questions (long or double), use the math operators listed in the table below.
Item Description
= Equal to
<> Unequal to
< Less than
<= Less than or equal to
> Greater than
>= Greater than or equal to
Routing(Web)
AmtSpentAccom.Ask()
TypeAccom.Ask()
End If
End Routing
56
Survey Programming Fundamentals Chapter 5 Basic Routing Logic
Boolean Questions
Boolean questions have values of True or False, so they can easily be checked with a simple statement:
Name.Response.Value = condition
Item Description
Name Unique identifier for the item within your questionnaire. They must start with a
letter or underscore ( _ ) and contain only alphanumeric characters or the
symbols @, $, #, or _
Response.Value Current response to the question identified by name above
condition True (checkbox was checked) or False(checkbox was left empty)
Text Questions
With text questions you can test whether the response matches a pattern. The expression format is:
Item Description
Name Unique identifier for the item within your questionnaire. They must start with a
letter or underscore ( _ ) and contain only alphanumeric characters or the
symbols @, $, #, or _
like Keyword to indicate you are trying to match a test pattern
pattern Represents the text with which the response is to be compared. An underscore
(_)in the text matches any single character, and a percent sign (%) matches any
number of characters, including zero
The following code checks text questions to see if it contains the word, Luftansa. If it does, then it
follows up with another question.
TimesWithLuftansa "And how many times over the past year have you flown Luftansa?"
long [0..365];
End Metadata
Routing(Web)
BestAirTravel.Ask()
If BestAirTravel.Response.Value Like "%Luftansa%" Then
TimesWithLuftansa.Ask()
End If
End Routing
57
Chapter 5 Basic Routing Logic Survey Programming Fundamentals
Categorical Questions
For singleresponse categorical questions, you may find simple expressions to suffice, such as
Name.Response.Value={Yes} . However, things will get complex, and youll need the Dimensions
functions to make more advanced logic statements.
Dimensions functions for categorical responses were created specifically for Dimensions scripting. We
will cover 3 basic functions for routing purposes, ContainsAll , ContainsAny and AnswerCount.
ContainsAll
Identifies whether a category list contains all of the categories in a given list. And condition for an
individual question.
Name.ContainsAll({ID1, IDn},parameter)
Item Description
Name Represents the question name
ContainsAll Dimensions function testing whether a list of categories are all contained in the
named question. (And condition)
ID1, IDn Unique identifying name for the response.
parameter Represents an optional parameter. If the parameter is set to true, then the
function will be true only if the response contains all of the categories and no
others (exclusive). If the parameter is set to false (default), then the function
will be true if the response contains all of the responses listed, regardless of
other responses chosen from the question.
Example
CountryVisited.ContainsAll({NorthAmerica,SouthAmerica})
This statement would be true if a respondent chose both North America and South America in the
CountryVisited question, regardless of other responses chosen from the question.
58
Survey Programming Fundamentals Chapter 5 Basic Routing Logic
Example
CountryVisited.ContainsAll({NorthAmerica,SouthAmerica}, true)
This statement would be true if a respondent chose both North America and South America AND did
not choose any other responses in CountryVisited.
ContainsAny
Identifies whether a category list contains one or more categories in a given list. Or condition for an
individual question.
Name.ContainsAny({ID1, IDn},true)
Item Description
Name Represents the question name
ContainsAny Dimensions function testing whether any of the list of categories are contained
in the named question. (Or condition)
ID1, IDn Unique identifying name for the response.
True Represents an optional parameter. If the parameter is set to true, then the
function will be true only if the response contains any of the categories and no
others (exclusive). If the parameter is set to false (default), then the function
will be true if the response contains any of the responses listed, regardless of
other responses chosen from the question.
Example
CountryVisited.ContainsAny({NorthAmerica,SouthAmerica})
The above statement would be true for respondents choosing North America, South America, or both.
59
Chapter 5 Basic Routing Logic Survey Programming Fundamentals
AnswerCount
The function AnswerCount counts the number of mentions chosen for a specific categorical question.
Name.AnswerCount()
Item Description
Name Represents the question name
AnswerCount Dimensions function returning how many responses have been chosen in the
named categorical question.
It returns a numeric value, so you would use numeric operators to test the result of the function.
End if
The example above states that if the number of answers mentioned in the categorical question,
CountryVisited, is greater than 3, then ask the followup question.
Logical Operators
You can also use the logical operators of Not, And, Or, and Xor to create more complex routing
conditions.
NOT
It is used to negate expressions. Its recommended to enclose the item to negate in parenthesis as
shown below.
Example
Not (TravelHelp.ContainsAny({Expedia}))
The above would be true if the respondent did not answer Expedia for the TravelHelp question.
60
Survey Programming Fundamentals Chapter 5 Basic Routing Logic
AND
Example
DaysTravelYr > 5 And TravelHelp.ContainsAny({Expedia})
The above will be true if the respondent traveled more than 5 days and used Expedia.
OR
Returns true when either or both parts of the expression are true.
Example
DaysTravelYr > 5 Or TravelHelp.ContainsAny({Expedia})
The above will be true if the respondent traveled more than 5 days or used Expedia.
XOR
Returns true when one part (but not both parts) of the expression are true.
Example
DaysTravelYr > 5 Xor TravelHelp.ContainsAny({Expedia})
The above will be true if the respondent traveled more than 5 days and did not use Expedia, or if the
respondent traveled 5 days or less and did use Expedia.
61
Chapter 5 Basic Routing Logic Survey Programming Fundamentals
Some find xor confusing, but it can save some syntax. The following statement is the equivalent of the
previous xor statement:
Example
(DaysTravelYr > 5 And (Not (TravelHelp.ContainsAny({Expedia}))) ) Or (DaysTravelYr <= 5 And
TravelHelp.ContainsAny({Expedia}))
As you can see when creating complex conditions with combinations of and, or, and not statements,
put parenthesis around things you want evaluated together.
If you need to refer to the special responses DK, REF, NA in a noncategorical question, you
need to refer to it as QuestionName.Response.Coded = {ID}, where ID is the ID of the special
response.
This may not always work, as there are multiple ways to write the statements. You will
notice the ScriptAssist may not always provide the proper choices. A good example would
be Dimensions functions, such as ContainsAny. The method used in this chapter,
Name.ContainsAny({Response}), does not provide script assistance. The fully documented
way, ContainsAny(Name.Response.Value,{Response}), will show parameters needed.
62
Survey Programming Fundamentals Chapter 5 Basic Routing Logic
Routing(Web)
Example ' Error handler
If Not IOM.Info.IsDebug Then On Error Goto DefaultErrHandler
Goto StartOfScript
DefaultErrHandler:
Dim errmsg, numerror
errmsg = "Script error at line " + CText(Err.LineNumber) + ", " + Err.Description
IOM.Log(errmsg, LogLevels.LOGLEVEL_ERROR)
If IOM.Info.IsTest Then
IOM.Banners.AddNew("ScriptErrMsg" + CText(numerror), errmsg)
numerror = numerror + 1
End If
Resume Next
StartOfScript:
' End error handler
End Routing
The IOM.Info.IsDebug prevents the error handler being enabled if the script is being run in
mrStudio.
On Error Goto DefaultHandler sends all erros to the error handler. When an error occurs, the
error handler writes the error message and the line number to the log file, IVW*.tmp.
IOM.Info.IsTest displays the message on the top of the current page.
The Resume Next line allows the interview to continue after an error.
63
Chapter 5 Basic Routing Logic Survey Programming Fundamentals
Exercise
Use the metadata file, Routing.mdd as your starting point. Complete the routing section and
routing/skip patterns shown below.
Yes
No (Skip to ItemsOwned)
PeopleCookFor Do you normally cook for any of the following at your home? Check all that apply.
(If CookMealWk is greater than or equal to 5 and PeopleCookFor question has adults, ask Wine)
Wine Do you ever serve wine with the meals you serve to others?
Yes
No
(If PeopleCookFor is both Children in HH and NonHousehold Member Children, ask AllergyKids)
AllergyKids Do any of the children you make meals for have food allergies?
Yes
No
64
Survey Programming Fundamentals Chapter 5 Basic Routing Logic
PrepTime On average, how much time do you devote to preparing a single meal?
30 minutes or less
3190 minutes
Over 90 minutes
Dont know
MealStrategy Please list some of your strategies for preparing meals so quickly.
Too short
Too long
Just right
Dont Know
65
Chapter 5 Basic Routing Logic Survey Programming Fundamentals
Bread Maker
Food Processor
Stand Mixer
Wok
Fondue Pot
None of These
Daily
Weekly
Monthly
Yearly
Never
(If CookAtHome is No, and UseItems not equal to Never, ask WhatUseFor)
WhatUseFor Please explain what you use your kitchen items for if you do not cook at home.
66
Survey Programming Fundamentals Chapter 6 Shared Lists
s
Including subheadings inn a list
{ID1 "AltText1",
IDn "AltTextn" } ;
Item Description
ListNamee Unique identifier for the shared list in the metadata. They must start with a
c
letter or underscore ( _ ) and contain only alphanumeric characterss or the
sy mbols @, $, #, or _
"Text" Optional text when list is used as a sublist.
Define Keyword to create a shared list
{ } Indicates the start of the categories for the define list
ID1, IDn Unique identifying name for the t response. This needs to be unique per
qu estion, not metadata
e s
file. Rules for the response names are the same as the
name
m of the qu estion.
AltText1, Optional text to show the respondent instead of the name of the question. This
AltTextn will apply when the name of the question is not the same as the text you wish to
show the respondent.
67
Chapter 6 Shared Lists Survey Programming Fundamentals
{use listname} ;
Item Description
Name Name of the Question
"Text" Text associated with the question (considered the label in the object model).
Categorical Keyword to create a question with categories for response choices.
[Min..Max] Optional parameters. Controls the minimum and maximum amount of
categories that can be chosen by a respondent. Default is open to any amount
of choices. Automatically issues an error message if the number of responses
chosen is below the minimum or above the maximum.
Use Keyword to include the categories from a define list in the question.
Listname Represents the name of the define list to use for the categories of the question.
ResortTypes define
Example {
Historical,
AmusementPark "Amusement Park",
Beach,
Adventure
};
ResortStayed "Of the following, which Resort types have you stayed at in the last year?"
Categorical [1..]
{ use ResortTypes };
You can use more than one list within the same question
You can create shared lists that are made up of other shared lists
You can use a shared list with a question in addition to adding other categories to that specific
question
68
Survey Programming Fundamentals Chapter 6 Shared Lists
Item Description
Name Name of the Question
"Text" Text associated with the question (considered the label in the object model).
Categorical Keyword to create a question with categories for response choices.
[Min..Max] Optional parameters. Controls the minimum and maximum amount of
categories that can be chosen by a respondent. Default is open to any amount
of choices. Automatically issues an error message if the number of responses
chosen is below the minimum or above the maximum.
Use Keyword to use the categories from a define list
listname1, Represents the name of the define lists to use for the sublist categories of the
listnameN question.
Sublist Keyword to designate the preceding define list as a subheading list
Sublistname1, Optional Text to display as the subheading Text. If not specified, will use label
SublistnameN specified in the define list.
69
Chapter 6 Shared Lists Survey Programming Fundamentals
The following example uses the concept of sublist using two define lists to create subheadings in the
categorical question.
CamporResortStayed "Of the following, which Resorts have you stayed at and what types
of camping have you participated in the last year?"
Categorical [1..]
{
use ResortTypes sublist "Resorts:" , use
CampingTypes sublist "Camping:", Noneofthese
"None of these" style (Indent = 0) NA
};
End Metadata
70
Survey Programming Fundamentals Chapter 6 Shared Lists
The example shows a None of these choice. This demonstrates that you can have additional
categories in a question outside of any define lists used.
Instead of stating the subheading text after the keyword sublist, this could have been
placed between the empty in the define lists.
71
Chapter 6 Shared Lists Survey Programming Fundamentals
72
Survey Programming Fundamentals Chapter 7 Sorting Categorical Response Lists
r
Ensure certain respon ses are not sorted
e
within a sorted list
Item Descripti n
Rotate o list is rotated by one category before each presentation of the
The category
list.
Randomize The category list is presented in randomized order.
Reverse The category
o list is reversed
e before each presentation. This means that thee list
is presented
e topdown to the first respondent,
e bottomup to the
t next, etc.
Ascending The category list is sorted in ascending alphabetical order.
Descending o list is sorted in descending alphabetical order.
The category
You can use any of the sorting features above in either the metadata or the routing sections as shown
in the next sections.
There is a difference using the randomize feature in the metadata and routing sections
when using the same response list for multiple questions. Using the metadata method will
hold the same pattern for each question per respondent; the routing method will change
the pattern for each question.
73
Chapter 7 Sorting Categorical Response Lists Survey Programming Fundamentals
Sorting in Metadata
To sort a question in the Metadata section, use any of the keywords for sorting following the curly
brackets of a category list.
Item Description
Name Unique identifier for the item within your questionnaire. They must start with a
letter or underscore ( _ ) and contain only alphanumeric characters or the
symbols @, $, #, or _
"Text" Text associated with the item (considered the label in the object model).
categorical Keyword to create a question with categories for response choices.
[Min..Max] Optional parameters. Controls the minimum and maximum amount of
categories that can be chosen by a respondent. Default is open to any amount
of choices. Automatically issues an error message if the number of responses
chosen is below the minimum or above the maximum.
{ } Indicates the start of the categories you wish the respondent to choose from for
the question
ID1, IDn Unique identifying name for the response.
AltText1, Optional text to show the respondent instead of the name of the question. This
AltTextn will apply when the name of the question is not the same as the text you wish to
show the respondent.
sortingkeyword Represents one of the sorting keywords rotate or rot; randomize or ran; reverse
or rev; ascending or asc; descending or desc
In the example below, adding the ran keyword randomizes the response list.
Souvenirs "Which of the following souvenirs do you prefer to purchase when on holiday
or vacation?"
categorical [1..]
{
Clothing,
Hats,
Postcards ,
SnowGlobes "Snow Globes"
} ran;
End Metadata
74
Survey Programming Fundamentals Chapter 7 Sorting Categorical Response Lists
Name.Categories.Order=orderconstants.osortingkeyword
Item Description
Name Represents the name of the question to sort
Osortingkeyword Represents one of the sorting keywords oAscending, oDescending, oCustom,
oRandomize, oReverse, or oRotate.
Routing(Web)
Example
Souvenirs.Categories.Order=orderconstants.oAscending
Souvenirs.Ask()
End Routing
Item Description
Fix Keyword to make the category prior to the keyword fixed in its original position,
regardless of the sort order
sortingkeyword Represents one of the sorting keywords listed in the previous section (example
ran)
75
Chapter 7 Sorting Categorical Response Lists Survey Programming Fundamentals
The following example will not sort the None of these option; it will stay at the bottom of the list. In
addition, the Other responses will always be the last in the series of items for their individual lists.
This also demonstrates a style being used to force the None of these response to be lined up with
the Subheadings instead of indented (indent=0). You will learn more about styles in Chapter 13
Controlling the Look of Your Survey.
76
Survey Programming Fundamentals Chapter 7 Sorting Categorical Response Lists
End Metadata
77
Chapter 7 Sorting Categorical Response Lists Survey Programming Fundamentals
Exercise
Update the following questions by adding the features highlighted below in your GroceryBill.mdd file
to include sorted categories.
StoreName What was the name of the store in which you shopped? (RANDOMIZE)
Walmart
Safeway
Kroger
Albertsons
Ahold USA
Delhaize
Publix
WinnDixie
Other (Specify)
ItemTypes Which of the following categories of groceries did you purchase on this shopping trip?
(RANDOMIZE BOTH THE GROUPS AND THE ITEMS WITHIN THE GROUPS)
Prepared Foods
Cheese/Olive Bar
Salad Bar
Deli Items
NonPrepared Foods
Meat/Seafood
Produce
Canned Goods
Pasta/Grains
None of These
78
Survey Programming Fundamentals Chapter 8 Restricting Responses
In this chapter we
w will:
Filter responses displayed
e on a questiono
based on previous
p answeers to questions
Filter Categories
The Filter property can be used to limit the categories displayed by a question in the routing section.
Routing(Web)
Name.Categories.Filter=condition
Name.Ask()
End Routing
Item Description
Name Unique identifier for the question
s name.
Categories Property (keyword) of the question denoting the responses
Filter Property (keyw ord) to state you are restricting the categories
e for the question
condition Represents anything that states the categories to display for the question
79
Chapter 8 Restricting Responses Survey Programming Fundamentals
Here is an example in which we are asking respondents to choose all the hotel chains they have stayed
in the past year. The followup question is Of those chains, which is your favorite? The response list
for the followup question is restricted to only the answers given in the first question.
End Metadata
Routing(Web) HotelChainStayed.Ask()
FavHotelChain.Categories.Filter=HotelChainStayed.Response.Value
FavHotelChain.Ask()
End Routing
80
Survey Programming Fundamentals Chapter 8 Restricting Responses
If you choose:
Special Responses of DK, REF, and NA are not filtered out automatically. In addition, if any
of those special responses are chosen, it skips the filtered question.
81
Chapter 8 Restricting Responses Survey Programming Fundamentals
How does the above work? The filters are based on the NAMES of the responses. While it is not
necessary to use shared lists for filtering, it is a good practice when the response lists are identical to
ensure that the names are also identical.
You do NOT need to have the lists identical to filter one question off another. mrInterview will simply
match what it can and disregards the rest. For instance, what if our lists were different:
HotelChainStayed "Choose the hotel chains you have stayed at this past year."
Example categorical [1..]
{
InterContinental,
Cendant,
Marriott,
Accor,
Choice,
Hilton,
DontKnow "Dont Remember" DK,
Refused "Prefer not to Answer" REF
};
FavHotelChain "Of the chains listed below in which you stayed, which one would you
most prefer to stay at again?" categorical
[1..1]
{
Accor,
Choice,
Hilton,
DontKnow "Dont Remember" DK,
Refused "Prefer not to Answer" REF
};
Routing(Web) HotelChainStayed.Ask()
FavHotelChain.Categories.Filter=HotelChainStayed.Response.Value
FavHotelChain.Ask()
End Routing
82
Survey Programming Fundamentals Chapter 8 Restricting Responses
If you choose:
As you can see, even though InterContinental was chosen, it does not show in the list, since it is not
part of the categories in FavHotelChain.
The above examples assume a naming convention for your category names. This is
recommended as names that identify the response make more sense across the entire
project lifecycle.
83
Chapter 8 Restricting Responses Survey Programming Fundamentals
Additionally, the filter does not need to be a single question. This can be a multitude of conditions,
such as Dimensions functions or specific categories.
Suppose our previous example was slightly different. What if we had two separate questions that
collected the hotels stayed in the past year. We will need two filter statements:
Filter the response from the first question so that it cannot be chosen from the 2nd list
Filter to combine both the first response and the 2nd response for the final question
HotelChainStayMost "Choose the hotel chain you have stayed at the MOST this past
Example year."
categorical [1..1]
{
InterContinental,
Cendant,
Marriott,
Accor,
Choice,
Hilton,
DontKnow "Dont Remember" DK,
Refused "Prefer not to Answer" REF
};
HotelChainStayed "Choose the other hotel chains you have stayed at this past year."
categorical [1..]
{
InterContinental,
Cendant,
Marriott,
Accor,
Choice,
Hilton,
DontKnow "Dont Remember" DK,
Refused "Prefer not to Answer" REF
};
FavHotelChain "Of the chains listed below in which you stayed, which one would you
most prefer to stay at again?"
categorical [1..1]
{
Accor,
Choice,
Hilton,
DontKnow "Dont Remember" DK,
Refused "Prefer not to Answer" REF
};
84
Survey Programming Fundamentals Chapter 8 Restricting Responses
Routing(Web)
HotelChainStayMost.Ask()
HotelChainStayed.Categories.Filter= HotelChainStayed.Categories
HotelChainStayMost.Response.Value
HotelChainStayed.Ask()
FavHotelChain.categories.filter=Union(HotelChainStayMost,HotelChainStayed)
FavHotelChain.Ask()
End Routing
See the Dimensions Development Library for more categorical functions to help with filters,
such as Difference and Intersection) DDL.chm::/categorical_functions.htm
85
Chapter 8 Restricting Responses Survey Programming Fundamentals
Name.Validation.MinValue = condition
Name.Validation.MaxValue = condition
Item Description
Name Metadata item name
Validation Property of questions
MinValue Property to control the minimum value allowed for a numeric question. Takes
precedence over what is stated as the minimum in square brackets on the
question.
MaxValue Property to control the maximum value allowed for a numeric question. Takes
precedence over what is stated as the maximum in square brackets on the
question.
Condition Represents the new value for the minimum or maximum limits
AmtSpentAir "And of that amount, how much was spent on airfares?" long [0..10000];
End Metadata
Routing(Web)
AmtSpentonHoliday.Ask()
AmtSpentAir.Validation.MaxValue = AmtSpentonHoliday.Response.Value
AmtSpentAir.Ask()
End Routing
86
Survey Programming Fundamentals Chapter 8 Restricting Responses
If you answered 5000 for the question AmtSpentonHoliday, then tried to submit an answer greater
than 5000 for AmtSpentAir, you would see the following:
87
Chapter 8 Restricting Responses Survey Programming Fundamentals
Exercise
Create a new metadata file called MealsOut.mdd. Make sure that:
You make shared lists for American Cuisine, International Cuisine, and restaurant attributes.
FavCuisine only displays the cuisines the respondent has ever eaten.
The answer to EatMealOut is not greater than the OrderMealOut amount.
Make the filter for the RestaurantOthr question be the responses not chosen in Restaurant1.
In addition, the other specify choice should show in RestaurantOther regardless if it was
chosen in Restaurant1.
CuisineEaten Which of the following types of Cuisine have you ever eaten?
American Cuisine
Barbecue
Cajun
Southern
Southwestern
International Cuisine
Italian
Russian
Polish
French
Caribbean
None of These
American Cuisine
Barbecue
Cajun
Southern
Southwestern
International Cuisine
Italian
Russian
Polish
French
Caribbean
None of These
OrderMealOut On average, how many meals per week do you order from a restaurant?
88
Survey Programming Fundamentals Chapter 8 Restricting Responses
EatMealOut Of those meals, how many do you eat at the restaurant, as opposed to home delivery or
carryout?
Restaurant1 When you eat at a restaurant, what one thing makes you want to return to the restaurant
again?
Good food
Good service
Nice Atmosphere
Large Selection of menu choices
Other (Specify)
RestaurantOthr What other factors also influence your decision to return to a restaurant?
Good food
Good service
Nice Atmosphere
Large Selection of menu choices
Other (Specify)
89
Chapter 8 Restricting Responses Survey Programming Fundamentals
90
Survey Programming Fundamentals Chapter 9 Multiple Questions on One Page
In this chapter we
w will:
q
Learn to place multiple questions on the
same screeen
You can place multiple questions on the same screen by using page or block statements.
Page metadata items reference other questions in the metadata to group them on the same
screen. If you are only trying to present more than one question on a screen, use a page.
Block metadata items contain other questions, similar to how a grid question can contain
multiple questions. The block type can be used to group a list of questions for presentation
and organizational purposes. For example, if you are trying to group questions together for use
with the analysis products mrTables and Desktop Reporter.
91
Chapter 9 Multiple Questions on One Page Survey Programming Fundamentals
Page
Creating a page in metadata creates a metadata item that states the questions you want displayed on
a screen and the order in which they should be displayed.
Item Description
Name Unique identifier for the item within your questionnaire. They must start with a
letter or underscore ( _ ) and contain only alphanumeric characters or the
symbols @, $, #, or _
"text" Optional text to show on the top of the screen
page Keyword to state we are grouping the following questions on the same page
QuestionName1, Represents the question names to display on the page together.
QuestionName2,
QuestionNamen
In the routing section, ask the page, not the individual questions:
Name.Ask()
Item Description
Name Name of the page metadata item
.Ask() Ask the questions listed in the page item
If you have many pages to create .Ask statements for, in the metadata viewer choose the
Page folder. Rightclick to choose Copy as Ask.
92
Survey Programming Fundamentals Chapter 9 Multiple Questions on One Page
The following is an example showing multiple demographic questions on the same screen.
Routing
Demos.Ask()
End Routing
93
Chapter 9 Multiple Questions on One Page Survey Programming Fundamentals
Block
Blocks are metadata items that contain the questions you want displayed together on a screen.
);
94
Survey Programming Fundamentals Chapter 9 Multiple Questions on One Page
Item Description
Name Represents the name of the block
"text" Optional text to show on the top of the screen
block Keyword to identify the item as a block
fields Start of the questions contained in the block
QuestionName1, Represents the questions contained inside the block
QuestionNamen
Name.Ask()
Item Description
Name Name of the block metadata item
.Ask() Ask the questions listed in the block item
As you can see in the following example, blocks are like containers which hold multiple questions.
HouseHold "Including yourself, how many people currently live in your household?"
long [1 .. 99];
Routing
Demos.Ask()
End Routing
95
Chapter 9 Multiple Questions on One Page Survey Programming Fundamentals
The previous code will look identical to the page example when viewed in the browser. However, the
metadata itself is very different. The block creates a separate item for blocks, as seen in the metadata
viewer:
Since your questions are now contained within a block, this will also affect how you refer to a question
in a block.
Blockname.Name
96
Survey Programming Fundamentals Chapter 9 Multiple Questions on One Page
The following example shows how you would refer to questions in a block within the routing section.
HouseHold "Including yourself, how many people currently live in your household?"
long [1 .. 99];
KidsAtHome "Do you have any children under the age of 18 living in your household?"
categorical [1..1]
{
Yes ,
No
};
End Metadata
Routing
Demos.Ask()
97
Chapter 9 Multiple Questions on One Page Survey Programming Fundamentals
Filtering a Page/Block
Using the same principles we learned with filtering, we can use a QuestionFilter to restrict the
questions shown to certain respondents.
Item Description
Name Name of the grid/loop question
QuestionFilter Property (keyword) to state you are restricting the questions of the page, or
block. This property also applies to grid/loop categories.
question1, Represents questions that will be added to the questionfilter and shown on the
questionN screen.
The following will not show the question asking to participate in future studies if they are already a
member of our panel group.
HouseHold "Including yourself, how many people currently live in your household?"
long [1 .. 99];
98
Survey Programming Fundamentals Chapter 9 Multiple Questions on One Page
Routing(Web)
Membership.Ask()
End Routing
Sorting a Page/Block
You can control the order of the questions with the same sorting options as shown previously. Simply
apply the sort keyword to the block or page name.
The following example would randomize the questions shown on the screen for the demos page or
block.
Routing(Web)
Example
' Using Demos from the previous examples
Demos.QuestionOrder=OrderConstants.oRandomize
Demos.Ask()
End Routing
99
Chapter 9 Multiple Questions on One Page Survey Programming Fundamentals
Exercise
Open the GroceryBill.mdd file and Save As CH09GroceryBill.mdd. Modify CH09GroceryBill.mdd so that:
GroceryDate and StoreName are on the same page using a PAGE statement
Generic, ItemsBought, and GroceryCost are contained within a BLOCK item
Review the metadata for the block to see how it has changed
100
Survey Programming Fundamentals Chapter 10 Repetitive Questions Loops & Grids
In this chapter we
w will:
n when to usee a grid or a loop in a
Understand
survey
Create metadata
e for grids
d and loops
Review different
f types of
o grids/loops
Please rate the following travel destinations on your inter st in visiting the location.
Extremely Somewhat
e Somewhat Extremely
t
Interested Interested Neutral Disinterested Disintereste d
Aruba { { { { {
Bermud a { { { { {
Florida { { { { {
Hawaii { { { { {
Fiji { { { { {
Costa Ri ca { { { { {
Thailand { { { { {
This is a good example of when to use the loop/grid metadata item. The properties this question has
that make it a loop/grid are:
All share the same responses (Extremely Interested, Somewhat Interested, etc.)
During analysis, we will want to see the results of each destination separately, but perhaps will
also want to see the results in summary in the format they appear in above.
You will also need to decide if you want to have the appearance of the questions to be exactly as we
see them above (i.e., on the screen all at once), or would we prefer that each question be on a
separate screen (i.e., "Please rate Aruba on your interest in visiting., Please rate Bermuda on your
interest in visiting., etc., ")
101
Chapter 10 Repetitive Questions Loops & Grids Survey Programming Fundamentals
Categorical Loops/Grids
We will define categorical loop/grids not by the type of questions they display, but by what defines the
number of times you repeat the questions. The first examples will show a list of categories defining
the number of times you will show the question in a loop/grid.
} fields
) expand grid;
Item Description
Name Unique identifier for loop/grid
"GridText" Optional text that will be displayed when the questions in the loop are asked
together on one screen.
Loop Keyword to mark a set of repeated questions and define the number of
repetitions required.
ID1 "Alt Text1", Defines the category list that controls the number of repetitions required. You
IDn"Alt Textn" define it in the same way as the category list for a categorical question.
Fields Keyword prior to the questions to be repeated in the loop
Question1, Questions that will be repeated based on the category list (ID1, ID2).
Questionn
LoopText1, Defines an optional label that will be displayed when the questions in the loop
LoopTextn are asked on individual screens.
{@} Represents the current category to display when the questions in the loop are
asked on individual screens.
expand Since mrInterview supports both a hierarchical and a flattened view of the
data, using the expand keyword means that the data is represented in both
formats (bounded).
grid Keyword that allows SPSS Dimensions applications and components to
recognize that the loop is a grid. Example would be printing grids using
mrPaper.
column Optional keyword to change the orientation of the category list to be the
columns of the grid instead of the rows. (Keyword row is the default.) Is
placed on the end of the metadata prior to the semicolon.
102
Survey Programming Fundamentals Chapter 10 Repetitive Questions Loops & Grids
Here is the syntax for the grid shown at the beginning of this chapter.
) expand grid;
End Metadata
Routing(Web)
InterestinLocation.Ask()
End Routing
103
Chapter 10 Repetitive Questions Loops & Grids Survey Programming Fundamentals
In the previous example, since we asked the question using the loopname.Ask(), the survey will appear
in this format:
If you want to change the orientation so that the destinations are across the top of the
screen, add the keyword column after the grid keyword.
104
Survey Programming Fundamentals Chapter 10 Repetitive Questions Loops & Grids
If we add text to the Rating question metadata and change the statement in the routing:
) expand grid;
End Metadata
Routing(Web)
InterestinLocation[..].Ask()
End Routing
105
Chapter 10 Repetitive Questions Loops & Grids Survey Programming Fundamentals
Then the survey will come up one question at a time on the screen. The first time you will see:
The main grid text (text prior to the keyword loop) will not show when the questions are asked
on individual screens.
The {@} will show the label of the current category, in this case, the destinations.
The [..] indicates that you want to step through each value in your categorical loop one at a
time.
If the above is not clear, think about how you would display just one of the questions in the
loop: InterestinLocation[{Aruba}].Ask()
Dim var
var.Ask()
Next
106
Survey Programming Fundamentals Chapter 10 Repetitive Questions Loops & Grids
Item Description
Dim Declares a temporary variable to be used within the routing section
var Represents a temporary variable name you create
LoopName Name of our metadata loop/grid
For Each Marks the start and end of a loop. In this case, the loop is doing whats inside
Next the for/next for each question in another element. In this case our
metadata loop/grid. Each time through the For Each/Next , var will be the
individual questions of the loop/grid and will be asked by the var.Ask()
statement.
Here is the previous example written with a For Each/Next loop instead of the [..] syntax. This will
display the same in the browser as the previous example.
) expand grid;
End Metadata
107
Chapter 10 Repetitive Questions Loops & Grids Survey Programming Fundamentals
Routing(Web)
Dim location
End Routing
To help understand this, when running this code stop on one of the loop questions and
choose the Expressions tab and Evaluate location.QuestionFullName. Or you can choose
the Locals pane and look at the current value of location.
The For Each/Next loop will prove helpful in more complex scenarios.
ExpenseCategories define
Example
{ Transportation,
Accomodations,
};
BusTravelSpent "In the past year, approximately how much did you spend in each
category listed below for business travel?" loop
long [0 .. ];
) expand grid;
108
Survey Programming Fundamentals Chapter 10 Repetitive Questions Loops & Grids
You can also have multiple questions within a grid. The following example expands on the last
example to include two columns of numeric boxes on the screen:
TravelSpent "In the past year, approximately how much did you spend in each category
listed below for business and leisure travel?" loop
{ use ExpenseCategories } fields
(
BusTravel "Business Travel"
long [0 .. ];
) expand grid;
Routing
TravelSpent.Ask()
End Routing
109
Chapter 10 Repetitive Questions Loops & Grids Survey Programming Fundamentals
110
Survey Programming Fundamentals Chapter 10 Repetitive Questions Loops & Grids
Numeric Loops
Another way to create repetitive questions in a grid/loop is to create a loop in which you set a number
to represent the loop driver.
fields
) expand grid;
Item Description
Name Unique identifier for loop/grid
"GridText" Optional text that will be displayed when the questions in the loop are asked
together on one screen.
Loop Keyword to mark a set of repeated questions and define the number of
repetitions required.
[n1..n2] Defines the number of times you want the loop to execute.
Fields Keyword prior to the questions to be repeated in the loop
Question1, Questions that will be repeated based on the category list (ID1, ID2).
Questionn
LoopText1, Defines an optional label that will be displayed when the questions in the loop
LoopTextn are asked on individual screens.
{@} Represents the current category to display when the questions in the loop are
asked on individual screens.
Expand Since mrInterview supports both a hierarchical and a flattened view of the
data, using the expand keyword means that the data is represented in both
formats.
Grid Display the question as a grid when the question is printed using mrPaper. No
effect in browser based interviews.
The categories shown in previous loop examples are replaced with numbers. There are various ways to
specify the numbers which will represent the repetitions of the loop.
111
Chapter 10 Repetitive Questions Loops & Grids Survey Programming Fundamentals
The following will produce a pair of questions asked about the respondents last three trips.
Accommodations "When you were traveling on Trip # {@}, which of the following types
of accommodations did you stay?"
categorical [1..]
{
Hotel,
Motel ,
BedBreakfast "Bed and Breakfast",
Hostels,
Resorts ,
OtherAccom "Other Accomodations" other
};
) expand grid;
End Metadata
Routing(Web)
Last3Trips[..].Ask()
End Routing
112
Survey Programming Fundamentals Chapter 10 Repetitive Questions Loops & Grids
113
Chapter 10 Repetitive Questions Loops & Grids Survey Programming Fundamentals
Exercise
Create a new metadata file, Meals.mdd for this exercise.
Think back to the last three meals of breakfast, lunch, and dinner that you consumed.
MealTime Thinking about the last [INSERT MEAL] you had, what time did you eat [INSERT MEAL]?
Made at home
Purchased from a restaurant
Calories How many calories do you estimate your last three meals of breakfast, lunch and dinner
contained?
Breakfast
Lunch
Dinner
HealthAttribs Please state your level of agreement with the following statements
Strongly Strongly
Agree Neutral Disagree
Agree Disagree
Breakfast is the most important meal of the day { { { { {
Eating fast food can be healthy { { { { {
I have a wellbalanced diet { { { { {
I dont eat a lot of sugar { { { { {
HealthComm Please add any additional comments you have about the importance of healthy foods
in restaurants.
114
Survey Programming Fundamentals Chapter 11 Debugging Tools within mrStudio
In this chapter we
w will:
p you troubleshoot
Review concepts to help h
your scriptt
Create your
u own macross
Some of the items within mrStudio which may help you in testing your scripts are the ability to:
115
Chapter 11 Debugging Tools within mrStudio Survey Programming Fundamentals
You will be prompted for the number of interviews you wish to produce and the number of attempts
the system should make per question.
This shows that the FriendRelate question only received 2 out of the possible 10 automatically created
responses. When investigated further, this makes sense, as there was a skip pattern around that
question. Other good things to look at in this view would be questions with no responses, which could
mean you forgot to ask the question.
116
Survey Programming Fundamentals Chapter 11 Debugging Tools within mrStudio
You can now choose the AutoAnswer icon or Tools Auto Answer Data Generation
You will still be prompted for the number of interviews you wish to produce and the number of
attempts the system should make per question.
117
Chapter 11 Debugging Tools within mrStudio Survey Programming Fundamentals
The first time you run this, you will now see the following screen asking you to choose the
datatype to create.
Choose your datatype and browse and name the new datafile.
If you choose to create a SPSS .SAV file, choose metadata type as none and just specify a
case data location and name.
118
Survey Programming Fundamentals Chapter 11 Debugging Tools within mrStudio
Now you will be able to Rightclick on DataSources and choose Change DataSource to choose which
datasource you want to create test data for.
119
Chapter 11 Debugging Tools within mrStudio Survey Programming Fundamentals
Setting Breakpoints
To find out what happens at critical points in your program, you need to stop execution at these points
and look at the contents of questions or temporary variables to see if they contain the correct values.
Points at which mrStudio stops to allow this investigation are called breakpoints.
To set a breakpoint, click on the grey area on the left side of the numbering in your routing section.
This should produce a large dot on that line as shown below:
You can use this feature in many ways. Many people test surveys and when they find a problem, they
want to stop and fix the problem and start retesting at that point.
This is an easy way to start using breakpoints. As your code becomes more complex, you will use
breakpoints to evaluate your code even more.
120
Survey Programming Fundamentals Chapter 11 Debugging Tools within mrStudio
To step through code, choose the F10 key or Debug Single Step.
Using the Locals pane (View Locals) you can view previous answers to questions as shown in the
picture below.
In addition, you can see the properties of questions, such as the appropriate styles or proper names for
elements of a question.
121
Chapter 11 Debugging Tools within mrStudio Survey Programming Fundamentals
Using the Expressions tab, you can view or set the values to questions or variables in order to further
test your script. (View Expressions). In the example below, we are setting the value of the
TravelItem question to test the if then routing pattern we have created.
122
Survey Programming Fundamentals Chapter 11 Debugging Tools within mrStudio
In mrStudio, choose Tools Macros. This will display the options shown below. Notice the 3 different
areas in which you can work with macros. For Interview Scripting, you should use:
123
Chapter 11 Debugging Tools within mrStudio Survey Programming Fundamentals
You can copy macros from one machine to another by copying the file,
124
Survey Programming Fundamentals Chapter 12 Conditioned Loops and Grids
v
Previous e within the loop
responses o
v
Previous q
e to a simple question
responses
outside
s the loop/grid
g
Previous
v responses
e to a different loop/grids
questions
u
A sublist o
of categories
If the response is Never, the respondent should not see the follow up question, Why do you
reference the travel guide, Lonely Planet? If we wish to repeat these pairs of questions for multiple
travel guides, then we must place the questions within a loop. The following loop demonstrates how
to write this logic within the routing section.
125
Chapter 12 Conditioned Loops and Grids Survey Programming Fundamentals
) expand grid;
End Metadata
Routing(Web)
Dim tguide
For Each tguide In TravelGuides
tguide.Read.ask()
If tguide.Read.Response.Value <> {Never} Then
tguide.WhyRead.Ask()
End If
Next
126
Survey Programming Fundamentals Chapter 12 Conditioned Loops and Grids
tguide is a temporary variable that will represent the categories of the loop (the travel guides)
For Each/next loop will loop through each tguide in our loop question, TravelGuides
tguide.Read.Ask() will ask just the question, read for each travel guide
The If statement checks the logic so that if the current value of tguides response to the read
question was not Never, then ask the followup question, WhyRead
Name.QuestionFilter=categories
Item Description
Name Name of the grid/loop question
QuestionFilter Property (keyword) to state you are restricting the categories of the loop/grid
question
Categories Represents anything that states the categories you wish to display in the
loop/grid. Setting the filter equal to Null will set the filter to all valid categories.
The following is an example of a grid which will only show grid categories that are appropriate/logical
for the respondent.
AttendedResort "From the list below, please indicate which types of resorts you have
stayed at."
categorical [1..] {use ResortTypes};
127
Chapter 12 Conditioned Loops and Grids Survey Programming Fundamentals
RateResortLoop "Of the resorts you have stayed at, please rate them on your overall
satisfaction with your experiences at the resort." loop
{ use ResortTypes } fields
(
RateResort ""
categorical [1..1]
{ VerySatisfied "Very Satisfied",
SomewhatSat "Somewhat Satisfied" ,
SomewhatDisSat "Somewhat Dissatisfied" ,
VeryDissatisfied "Very Dissatisfied"
};
) expand grid;
End Metadata
Routing(Web) AttendedResort.Ask()
RateResortLoop.QuestionFilter=AttendedResort.Response.Value
RateResortLoop.Ask()
End Routing
If you choose:
128
Survey Programming Fundamentals Chapter 12 Conditioned Loops and Grids
You will only have the responses chosen as the categories of the grid:
Why are you satisfied overall with the [INSERT RESORT TYPE+? This should only be asked of the resort
types they responded very satisfied or somewhat satisfied.
129
Chapter 12 Conditioned Loops and Grids Survey Programming Fundamentals
Create a loop question containing the text question above to hold the answer separately for
each resort type (a single question would not be sufficient).
Create a QuestionFilter for the loop that holds the text question. This QuestionFilter should
contain only the resorts (categories) in which the respondent rated Very Satisfied or Somewhat
Satisfied in the previous loop.
RateResortLoop "Of the resorts you have stayed at, please rate them on your overall
satisfaction with your experiences at the resort." loop
{ use ResortTypes } fields
(
RateResort ""
categorical [1..1]
{ VerySatisfied "Very Satisfied",
SomewhatSat "Somewhat Satisfied" ,
SomewhatDisSat "Somewhat Dissatisfied" ,
VeryDissatisfied "Very Dissatisfied"
};
) expand grid;
) expand grid;
End Metadata
130
Survey Programming Fundamentals Chapter 12 Conditioned Loops and Grids
Routing(Web)
RateResortLoop.Ask()
Dim Resort
Dim WhyLoopFilter
WhyLoopFilter = {}
For Each Resort In RateResortLoop
If Resort.RateResort.ContainsAny({VerySatisfied, SomewhatSat}) Then
WhyLoopFilter = WhyLoopFilter + CCategorical(Resort.QuestionName)
End If
Next
WhyLoop.QuestionFilter = WhyLoopFilter
WhyLoop[..].Ask()
End Routing
You must set the variable WhyLoopFilter to {} so that it starts as a filter with nothing in it.
Name.QuestionFilter=Name.Categories.sublistname
Item Description
Name Name of the grid/loop question
QuestionFilter Property (keyword) to state you are restricting the categories of the loop/grid
question
Categories Keyword for the categories of the grid/loop
sublistname Name of the sublist you wish to show in the grid/loop
The following example asks if the respondent primarily travels for business, leisure or both. Based on
this response, the followup grid question will display a define list with business travel attributes
(BusinessAttribs), leisure travel attributes (LeisureAttribs) or both lists.
131
Chapter 12 Conditioned Loops and Grids Survey Programming Fundamentals
132
Survey Programming Fundamentals Chapter 12 Conditioned Loops and Grids
Routing(Web)
Example primarytravel.Ask()
Select Case PrimaryTravel.Response.Value
Case {Business}
TravelAttribs.QuestionFilter=TravelAttribs.Categories.BusinessAttribs
Case {Leisure}
TravelAttribs.QuestionFilter=TravelAttribs.Categories.LeisureAttribs
Case Else
TravelAttribs.QuestionFilter= Null
End Select
TravelAttribs.Ask()
End Routing
Only the Business sublist for the TravelAttribs if they primarily travel for business
Only the Leisure sublist for the TravelAttribs if they primarily travel for leisure
Both lists if they chose Both for the primarytravel question
The QuestionFilter lines above are set equal to the Question.Categories.sublistname if the
respondent only chose business or leisure.
The QuestionFilter was set to Null when the respondent chose both. Null resets the
QuestionFilter so that all categories are shown. Another alternative is to set the filter to the
questions definedcategories.
Using the sublists as shown above does limit your abilities to sort, as the sublists can be
sorted within themselves, but you cannot sort the two sublists together. If sorting is an
issue and you wish to use a sublist as a filter, see filterbysublist.mdd on your CD for an
advanced function to eliminate the problem. This example dynamically creates a filter from
the categories in a sublist, instead of using the sublist for the filter directly.
133
Chapter 12 Conditioned Loops and Grids Survey Programming Fundamentals
Exercise
Use the metadata file, Restaurant.mdd. The metadata has been completed; please add the routing
section and logic as stated below.
(Ask the next two questions (Eaten & OftenEat) for each of the restaurant types of:
Upscale Restaurants)
Yes
No
OftenEat (If Yes) How often do you eat in [INSERT TYPE OF RESTAURANT]?
Daily Weekly
Monthly
Yearly or less
(Ask only if they said Yes to the type of Restaurant in the Eaten Question)
FoodQuality Please rate your overall satisfaction with the quality of food obtained in the following
types of restaurants.
134
Survey Programming Fundamentals Chapter 12 Conditioned Loops and Grids
(If Yes to Fast Food in Eaten Question, ask ChainAware and FastFoodQual.)
ChainAware Which of the following fast food chains have you eaten at?
Wendys
McDonalds
Burger King
Arbys
InNOut Burger
None of these
FastFoodQual Please rate your overall satisfaction with the quality of food obtained in the following
fast food restaurants.
135
Chapter 12 Conditioned Loops and Grids Survey Programming Fundamentals
136
Survey Programming Fundamentals Chapter 13 Controlling the Look of Your Survey
In this
t chapter we will learn:
w
Different ways to change the overall
appearancec of your survey
1) HTML Templates (including Cascading Style sheets and .xml files). These are special HTML
pages that are applied to your survey.
2) Styles within the script. These are scripting properties added to either the metadata or the
routing section.
For example, if you format a specific question with a style in a way that contradicts what is in the HTML
template, then the question style will override the templates format for that question.
Now that you have a basic understanding of how templates and styles are applied to the survey, lets
take a closer look at each aspect.
Templates
Templates are HTML pages which have special mrInterview tags that represent the different parts of
a survey. Templates control the layout of the mrInterview page separate from the text of your
questionnaire as you created it in the metadata. This allows you the flexibility to create standard
templates for reuse in many projects. You can also use more than one template within a survey.
137
Chapter 13 Controlling the Look of Your Survey Survey Programming Fundamentals
Layout Template: Defines one page/screen layout. This template is usually created in a way in
which you can apply this to multiple studies if you want them to all have the same basic look.
Also, this does not necessarily mean that you have to create a completely new template file if
you want to vary just one aspect of the layout for a particular part of an interview or for a
different project. If the basic page layout is the same, you can create subtemplates for the
aspects that change.
SubTemplate: A template file that defines the layout of one aspect of the page. For
example, you can create subtemplates for questions (question and response texts), errors,
banners, navigation bars, and grids. The main page layout template (listed in the previous
bullet point) contains a basic tag indicating where the various components belong and the sub
templates define the exact layout for each component. You specify which subtemplates are to
be used by naming them in the routing section of the interview script or in the main layout
template.
Localized Template: Used for organizations that create surveys for people in multiple regions
of the world. Localized templates allow you to set the language of an interview based on the
respondent's browser language, and the language can be changed in the interview script. The
interviewing program passes the language to the HTML Player, which searches for the
appropriate template in that languages folder and then in the project folder.
In addition all three template types can be assigned globally or at a project level. The order in which
mrInterview looks for templates is as follows:
Because of all the variables listed above, you will want to thoroughly test your scripts in many different
ways to ensure that the proper look is being applied to your survey.
This course will only discuss how to apply the templates, not how to create the templates.
For more information, see the DDL: DDL.chm::/interviewscripting_templates_writing.htm
138
Survey Programming Fundamentals Chapter 13 Controlling the Look of Your Survey
Routing(Web)
IOM.LayoutTemplate = "templatename.htm"
Name.Ask()
Item Description
IOM.LayoutTemplate Keywords to signify you are adding a template style to the survey from this
point forward in the routing section
templatename.htm The actual name of the template to apply
If a question is tied to a specific template or subtemplate (such as javascript logic to check a specific
question, or a complex question style), you may choose to add the template to the metadata:
Name "text"
Item Description
Templates(Question=) Keywords to signify you are adding a template style to this specific question in
the metadata
Templatename.htm Represents the actual name of the template to apply
questiontype Represents the questions type (categorical, long, text, etc.) Note that the
template goes before the question type keyword.
139
Chapter 13 Controlling the Look of Your Survey Survey Programming Fundamentals
Example Routing(Web)
IOM.LayoutTemplate= "Card_Blue_TopAndBottomErrors.htm"
InterestinLocation.Ask()
BusTravelSpent.Ask()
TravelSpent.Ask()
HotelChainStayMost.Ask()
HotelChainStayed.Categories.Filter = HotelChainStayed.Categories
HotelChainStayed.Ask()
FavHotelChain.Ask()
End Routing
You can drastically change the appearance of a question with templates. mrStudio displays the
templates as they will appear when activated to mrInterview.
When reviewing your templates, you can choose to see a full browser view as opposed to the
smaller window within mrStudio, by changing the Use Builtin Browser option to False
under Tools Options. However, with this option you cannot use the F5 Auto Answer
feature easily.
Folders
The Dimensions Development Library provides you with example templates to use and modify. These
are included by default in C:\Program Files\SPSS Dimensions\DDL\Scripts\Interview\Templates
folder.
140
Survey Programming Fundamentals Chapter 13 Controlling the Look of Your Survey
If you have templates from previous versions of mrInterview, you need to ensure the
templates are XHTML or perfectly formed HTML. In the toolbar, choose HTML tidy to have
mrStudio try to clean up your code. This may not always work 100%, but is may be worth
seeing what the results are. Make a backup of your template files before attempting HTML
tidy.
Make sure that when you activate the study in mrInterview that you have included any project
specific templates you have been using locally in mrStudio.
Styles
Styles allow us to control the many formatting aspects of survey items from inside our survey script. We
can use styles on such items as questions, categories, labels and navigation controls. There are two
major groups of styles:
Default Styles: Default styles are settings that get applied to an entire group of survey items.
For example, default styles would be used to make changes to all the question text font for
that script.
Question Styles: Question styles are used to format items for specific questions.
In practice you should use default styles to perform the bulk of your formatting with styles. Use
question styles to apply unique or question specific formatting. It is recommended that you declare
your default styles at the top of the routing section of the survey. However, you can change the
settings of the default styles at any time in your survey.
Complete details regarding the available options of the styles object can be found in the
DDL: IOMLib.chm::/IStyle.html
Default Styles
There are six types of default styles and each group has a number of subtypes. For this introductory
course, we will focus only on the main default styles:
Default
Labels
Categories
Grids
Navigation
Questions
While each of these different areas represents a different area for potential formatting you should also
be aware of the interaction between the areas. The style settings from one area will cascade to other
style objects. The following is the order of precedence:
141
Chapter 13 Controlling the Look of Your Survey Survey Programming Fundamentals
1) DefaultStyles.Default
2) DefaultStyles.Label
3) DefaultStyles.Navigation and DefaultStyles.Categories
4) DefaultStyles.Questions
5) DefaultStyles.Questions.Labels
6) DefaultStyles.Question.Categories and DefaultStyles.Grids
For example, if we set the font differently in the default and labels sections, the labels section will be
the setting that is used. Lets review some of the different areas of a survey in which styles can be
applied.
Default
The default style is the style settings that all other styles are derived from. So these settings will form
the basis for all other default style types and/or question style settings.
IOM.DefaultStyles.Default
Example Routing(Web)
IOM.LayoutTemplate= "Card_Blue_TopAndBottomErrors.htm"
IOM.DefaultStyles.Default.Font.Family = "Tahoma"
InterestinLocation.Ask()
End Routing
The example above would set all text to be Tahoma for this study, overriding what has been set in the
template.
142
Survey Programming Fundamentals Chapter 13 Controlling the Look of Your Survey
Categories
The category default styles section is used to apply formatting to categorical responses.
IOM.DefaultStyles.Categories[CategoryStyleTypes.CategoryStyleTypeEnum]
CategoryStyleTypeEnum Description
csSingle Single response categorical.
csMulti Multiresponse categorical.
csExclusive Exclusive response categorical.
csList Subheading Text.
Example Routing(Web)
IOM.DefaultStyles.Categories[CategoryStyleTypes.csExclusive].Label.Font.Effects = _
FontEffects.feBold=null
ModeofTravel.Ask()
End Routing
The code above will turn all responses marked with the keywords exclusive, DK, REF, or NA to be
unbold.
143
Chapter 13 Controlling the Look of Your Survey Survey Programming Fundamentals
Grid
Default grid styles are used to control the format of grid questions. It allows us to specify formatting
for column/row headings as well as alternating columns/rows.
IOM.DefaultStyles.Grids[GridStyleTypes.GridStyleTypesEnum]
Example Routing(Web)
144
Survey Programming Fundamentals Chapter 13 Controlling the Look of Your Survey
InterestinLocation.Ask()
End Routing
This code has been written in a With/End With block. The With/End With statement allows you to
specify information that will be added to the beginning of each line that starts with an open dot (.)
within the block. If there is not an open dot, then the information on the With line is not added. The
previous code will format all grids within the project with the properties specified. There is no
template applied to the picture below, only the styles specified above.
145
Chapter 13 Controlling the Look of Your Survey Survey Programming Fundamentals
Labels
Label default styles allow us to specify formatting for different types of labels. For example, we may
want all question labels to use a different size font than the category labels.
IOM.DefaultStyles.Labels[LabelStyleTypes.LabelStyleTypesEnum]
The code below will make all question text to have a font size of 24.
Example Routing(Web)
IOM.DefaultStyles.Labels[LabelStyleTypes.lsQuestion].Font.Size = 24
AmtSpentYr.Ask()
End Routing
Navigation
Default navigation styles can be used to format the look and feel of the navigation buttons.
IOM.DefaultStyles.Navigation
Example Routing(Web)
IOM.DefaultStyles.Navigation.BgColor = "#0099FF"
AmtSpenYr.Ask()
End Routing
The code above will create a blue background color on the navigation buttons.
146
Survey Programming Fundamentals Chapter 13 Controlling the Look of Your Survey
The number that represents the color is a hexadecimal color value and is commonly used to
create a very specific color. You can find many websites that provide these color codes.
Search for terms like web safe colors.
Questions
Question default styles allow you to define formatting specific to the type of question being displayed.
IOM.DefaultStyles.Questions[QuestionStyleTypes.QuestionStyleTypesEnum]
For example the following can be used to make all "other specify" textboxes a certain size.
Example Routing(Web)
IOM.DefaultStyles.Questions[QuestionStyleTypes.qsOther].Style.Width = 220
HotelChainStayed.Ask()
End Routing
147
Chapter 13 Controlling the Look of Your Survey Survey Programming Fundamentals
Question Styles
The same types of styles we discussed as default can be applied at the question level. The use of
question styles should be minimal, for very specific formatting needs. This section will discuss some
common questionspecific formatting needs.
Categorical Questions
With a categorical question you may want to display the available categories in multiple columns or
using a list box or combo box rather than the traditional checkboxes or radio buttons.
The following example will create 2 columns of responses instead of a single column.
Example Routing(Web)
HotelChainStayed.Style.Columns = 2
HotelChainStayed.Ask()
End Routing
The following example will create a dropdown list. Note that the categories have a subheading of
Select One. This is done so that the respondent must choose an answer, since the subheading is not
a valid response.
148
Survey Programming Fundamentals Chapter 13 Controlling the Look of Your Survey
Routing(Web)
Souvenirs.Style.Control.Type = ControlTypes.ctDropList
Souvenirs.Ask()
End Routing
You can also control the column width for the droplist or combo box with:
Name.Style.Width
Text Questions
For a text question you may want to control the width and height of the textbox generated. The
following will modify the width and height of the question.
Example Routing(Web)
WhySouvenir.Style.Width=400
WhySouvenir.Style.Height=50
WhySouvenir.Ask()
End Routing
You can also change the type of textbox that will be created:
TextQ.Style.Control.Type = ControlTypes.ctSingleLineEdit
To mask what is typed in the box with dots instead of the characters:
TextQ.Style.Control.Type = ControlTypes.ctPassword
149
Chapter 13 Controlling the Look of Your Survey Survey Programming Fundamentals
Metadata Styles
When a style is specific to a question, it may be better to apply the style to the question directly in the
metadata. The options available are the same as in the routing, but have a slightly different syntax.
The code below will orient the responses horizontally (orientation = row) and replaces the buttons and
text with an image.
End Metadata
150
Survey Programming Fundamentals Chapter 13 Controlling the Look of Your Survey
Custom Controls
Custom controls are a type of subtemplate that generates an interactive control that respondents can
use to answer a question. For example, if you have a date question you may want the respondent to
see a calendar. You could have the respondent flip through a calendar and then click on the date to
answer the question.
For an example of a custom control, review the calendar example in the DDL project,
C:\Program Files\SPSS Dimensions\DDL\Scripts\Interview\Projects\NewFeature.mdd
XHTML in Labels
We have seen that templates allow us to control the overall look of a survey page. We can use styles to
format individual labels or other survey items. However, sometime you may need to format just a
single word on a label. This type of granular formatting falls outside of templates and styles. We can
use XHTML within our metadata file to perform this type of formatting.
What is XHTML?
XHTML is a markup language based on HTML. The primary difference is the need for all tags to be well
formed. This means that all tags must have an opening and closing tag.
Here are a few basic tags that may prove useful within your script:
Tag Description
<b>text</b> Bold Tag
<i>text</i> Italic Tag
<u>text</u> Underline
<br /> Carriage Return
151
Chapter 13 Controlling the Look of Your Survey Survey Programming Fundamentals
TravelItem "From the list below, which <b>one</b> item would you most want to bring
Example with you on a leisure trip?"
categorical [1..1]
{
Camera ,
Map,
ComfortableFootwear "Comfortable Footwear",
FriendTravelCompanion "Friend/Travel Companion"
};
It is recommended that you only include XHTML tags when none of the other formatting options
provide a suitable solution. This is due to that fact that these tags can mean additional work when
relating to translation and/or reporting.
152
Survey Programming Fundamentals Chapter 13 Controlling the Look of Your Survey
Exercise
Open the Meals.mdd file and Save as MealsWithStyle.mdd
As time allows format all the grids to have the following look:
Hints:
153
Chapter 13 Controlling the Look of Your Survey Survey Programming Fundamentals
154
Survey Programming Fundamentals Chapter 14 Text Substitutions and Text Headings
In this chapter we
w will:
Display n answer to a previous question in
a the off the survey
text
{#Name}
Item Description
Name Name of the
h question that contains the response you want to display
Souvenirs "Which of the following souvenirs do you prefer to purchase when on holiday
Example or vacation?"
categorical [1..1]
{
Clothing ,
Hats,
Postcards,
SnowGlobes "Snow Globes"
} ran;
155
Chapter 14 Text Substitutions and Text Headings Survey Programming Fundamentals
If Snow Globes was chosen in the Souvenir question previously, the WhySouvenir question will appear
as:
If you are inside a loop and you want to display the item driving the loop, use the {@} sign.
156
Survey Programming Fundamentals Chapter 14 Text Substitutions and Text Headings
If the question is within a loop/grid and you need to reference it outside the loop, then the reference is
slightly different. You need to use the root level operator \. in the syntax:
{#\.LoopName[{LoopCategory}].InsideQuestion}
Item Description
Loopname Name of the loop
LoopCategory Specific loop/grid slice you wish to display the answer to
InsideQuestion Question within the loop/grid
The following will display the response to a specific grid slice in the follow up text question.
End Metadata
157
Chapter 14 Text Substitutions and Text Headings Survey Programming Fundamentals
Insert Text into the Metadata that will be controlled in the routing section
There will be other times in which you will control the text to be shown instead of redisplaying a
previous answer. To achieve this, you need to use a text insert. There are two parts to creating this
item. Add a marker in the metadata to represent the text you wish to insert, and then create a
reference to this within the routing.
End Metadata
Routing(Web)
OR
Name.Ask(Value)
End Routing
Item Description
Name Name of the metadata item that contains the placeholder or Marker
Text Text associated with the item
{Marker} or Represents the variable you created to be the placeholder for the text you want
["Marker"] to insert. As shown above, it is referenced differently in the metadata vs. the
routing.
Type Identifies the item for its functionality (categorical questions, text only items,
etc.)
Parameters This varies by item type, but an example would be the responses to a question.
Value Represents the text you want to insert in Marker. We recommend making the
text to be inserted an info item in the metadata for ease of translation.
158
Survey Programming Fundamentals Chapter 14 Text Substitutions and Text Headings
The following example will substitute text for the ExplainChain question based on if the respondent
chose one answer or many answers to the HotelChainStayed question. Notice the text to be
substituted is stored in info items in the metadata. This is a good practice if the study is to be done in
multiple languages.
ExplainChains "Please give a brief explanation why you chose to stay at {Chain} as
opposed to others in the past year."
text [1..];
End Metadata
Routing (Web)
HotelChainStayed.Ask()
If Not(HotelChainStayed.ContainsAny({DontKnow,Refused})) Then
If AnswerCount(HotelChainStayed) = 1 then
ExplainChains.Label.Inserts["Chain"].Text = OneChain.Label
Else
ExplainChains.Label.Inserts["Chain"].Text = Chains.Label
End If
ExplainChains.Ask()
End If
End Routing
159
Chapter 14 Text Substitutions and Text Headings Survey Programming Fundamentals
There is an alternative to the method for text substitution shown above. You can also add the insert
reference into the ask statement. The example below shows the previous insert example, but using
the alternative method.
ExplainChains "Please give a brief explanation why you chose to stay at {Chain} as
opposed to others in the past year."
text [1..];
End Metadata
Routing (Web)
HotelChainStayed.Ask()
If Not(HotelChainStayed.ContainsAny({DontKnow,Refused})) Then
If AnswerCount(HotelChainStayed) = 1 then
ExplainChains.Ask(OneChain.Label)
Else
ExplainChains.Ask(Chains.Label)
End If
End If
End Routing
160
Survey Programming Fundamentals Chapter 14 Text Substitutions and Text Headings
Here is an example that gets rid of the extraneous text that mrInterview places in a text insert for a
previous question when the answer is an other specify. You do not use the standard {#Name}, but
instead create a text insert with a condition to check for the other.
Routing (Web)
TypeAccom.Ask()
HowFreqStay.Label.Inserts["Accom"]=TypeAccom.OtherAccom
else
HowFreqStay.Label.Inserts["Accom"]=TypeAccom.Response.Label
end if
HowFreqStay.Ask()
End Routing
161
Chapter 14 Text Substitutions and Text Headings Survey Programming Fundamentals
Text Headings
You may wish to include headings that are applied to a single question or multiple screens. This can be
achieved by creating a banner. In the routing section, place the following statement:
Name.Banners.AddNew("BannerName", InfoName.Label)
IOM.Banners["BannerName"].Text = NewInfoName.Label
To remove a banner:
Name.Banners.Remove("BannerName")
Item Description
Name Name of the question or page to apply the heading. This can also be IOM to
use the same heading for multiple screens.
BannerName Unique name for the banner. Must follow standard naming conventions.
InfoName.Label, Name of the info item holding the text you wish to display. You can also choose
NewInfoName.Label to place specific text in double quotes within this item.
When adding banners, it is recommended that you place the text in info items instead of directly in the
routing section. This allows your surveys to be easily translated into multiple languages or contexts. In
the example below, we are adding one banner and changing its text during the survey to accommodate
the different sections.
162
Survey Programming Fundamentals Chapter 14 Text Substitutions and Text Headings
FavHotelChain "Of those chains, which one would you most prefer to stay at again?"
categorical [1..1]
{
InterContinental ,
Cendant,
Marriott,
Accor,
Choice,
Hilton,
OtherHotel "Other Hotel Chain" Other,
DontKnow "Dont Remember" DK,
Refused "Prefer not to Answer" REF
};
) expand grid;
End Metadata
163
Chapter 14 Text Substitutions and Text Headings Survey Programming Fundamentals
Routing (Web)
IOM.DefaultStyles.Labels[LabelStyleTypes.lsBanner].Font.Size = 24
IOM.Banners.AddNew("Header",HotelText.Label)
HotelChainStayed.Ask()
FavHotelChain.Categories.Filter= HotelChainStayed.Response.Value
FavHotelChain.Ask()
IOM.Banners["Header"].Text = DestinationText.Label
Dim location
For each location in InterestinLocation
location.ask()
Next
End Routing
The above example will display different headings for the different screens. We have also added a
default style to increase the font size of the Banner Text as shown below:
164
Survey Programming Fundamentals Chapter 15 Enhancing Survey Flow
In this chapter we
w will:
t initial answers
Preassign the e to questions.
Allow for an
n answer to be tthe default response
As stated above, mrInterview requires a response to each question. To override this option, you must
do 2 things:
Technically, there is still an answer for each question when you look at your data, however the
respondent will not have to respond to every question when it isnt necessary. A good use of this
feature would be a text question for optional comments. If the respondent did not have a comment,
they could simply choose the Next button to continue with the survey while mrInterview will record
the response as the predetermined default.
165
Chapter 15 Enhancing Survey Flow Survey Programming Fundamentals
Must Answer
The MustAnswer property can be applied at the IOM level, or on a question, page or block level.
Routing(Web)
Name.MustAnswer=False
The first statement would only apply to a specific question. The IOM statement above would prepare
all questions in the study to potentially not give an answer.
If mrInterview is not provided with a valid default answer, then the question will need to be
answered by the respondent before going to the next question. The exception for this is a
categorical question in which the minimum is not stated (example [..5]).
Default Answers
Default Answers can either be directly assigned by the programmer or use the preassigned default
value of No Answer. You can specify default answers in the metadata or routing sections.
In Metadata section:
Name "text" questiontype
DefaultAnswer(response);
Or Routing section:
Name.Response.Default=response
Item Description
Name Represents the question name
response Represents a valid response to the question (valid number for long questions,
category name for categorical questions, etc.)
166
Survey Programming Fundamentals Chapter 15 Enhancing Survey Flow
TravelSpent "In the past year, approximately how many much did you spend in each
Example category listed below for business and leisure travel?" loop
{
Transportation,
Accomodations,
FoodDrink "Food and Drinks",
OtherMisc "Other Miscellaneous"
} fields
(
BusTravel "Business Travel"
long [0 .. ] defaultanswer(0);
The result will not change with the addition of the defaults:
However if any cell is left blank, the default answer of zero will be entered instead of mrInterview
issuing an error message of Missing Answer(s).
167
Chapter 15 Enhancing Survey Flow Survey Programming Fundamentals
End Metadata
In the above example if the respondent doesnt answer the question, when they click the Next button
the answer will be recorded as Refused.
Routing(Web)
Example
Age.Response.Default={Refused}
Age.Ask()
End Routing
To use defaults options, the default answer must be set to a valid response for the question.
168
Survey Programming Fundamentals Chapter 15 Enhancing Survey Flow
The MustAnswer=False
A response assigned to the keyword NA
No defaultanswer response specified
Then the No Answer response will be hidden on the screen and if the respondent does not answer the
question and goes to the next screen, the No Answer response will be automatically chosen for that
question.
text
End Metadata
Routing(Web)
AddComments.MustAnswer=False
AddComments.Ask()
End Routing
As you can see above, there is not a No Comments reply on the screen due to the presence of the
MustAnswer=False and the lack of a DefaultAnswer specified.
169
Chapter 15 Enhancing Survey Flow Survey Programming Fundamentals
Initial Response
Instead of assigning default values when the respondent does not answer a question, you could have
an answer already assigned to the question when it is first shown to the respondent. This could be
used for large grids in which every response may not be applicable to the respondent. This is called an
initialanswer and is applied in the same way as the defaultanswer.
TravelSpent "In the past year, approximately how many much did you spend in each
Example category listed below for business and leisure travel?" loop
{
Transportation "Transportation",
Accomodations "Accomodations",
FoodDrink "Food and Drinks",
OtherMisc "Other Miscellaneous"
} fields
(
BusTravel "Business Travel"
long [0 .. ] initialanswer(0);
) expand grid;
This would be what the screen would look like when the respondent first sees the question:
170
Survey Programming Fundamentals Chapter 15 Enhancing Survey Flow
The code in the routing section to set the initial value for this complex question type would be:
) expand grid;
End Metadata
Routing(Web)
TravelSpent[..].BusTravel.Response.Initial=0
TravelSpent[..].LeisureTravel.Response.Initial=0
TravelSpent.Ask()
End Routing
Initial value will only be set the first time the respondent is shown the question, meaning if
they use the previous button to go back to questions, their answers will not be reset again
if they have changed the values. If you would like to always reset the values, then use the
QuestionName.Response.Value = response.
171
Chapter 15 Enhancing Survey Flow Survey Programming Fundamentals
Exercise
Open mealswithstyle.mdd file and make the following modifications.
Make HealthComm allow the respondent to move past the question without answering
Give the HealthAttribs loop initial values of Neutral
Add the following question after the HealthAttribs grid:
FastFoodComments Please elaborate on why you [AGREE/DISAGREE] with the statement
Eating fast food can be healthy.
Respondents who chose Neutral for the attribute Eating fast food can be healthy
should not be asked the FastFoodComments question.
For the insert AGREE OR DISAGREE, insert the word agree if the respondent chose
Strongly Agree or Agree for the Eating fast food can be healthy attribute; insert
disagree if the respondent chose Strongly Disagree or Disagree.
(Hint: If you need help determining how to reference one attribute within a grid
outside the grid, refer to the information item on page 106.)
172
Survey Programming Fundamentals Chapter 16 Customizing the Standard Error Messages
In this chapter we
w will:
o
Learn the keywords associated with he
standard error messagess
r message or all
Change he standard error
surveys
Each standard error message has a name associated with it and is listed in the table below.
173
Chapter 16 Customizing the Standard Error Messages Survey Program
You can change the messages associated with the errors in 3 ways:
174
Survey Programming Fundamentals Chapter 16 Customizing the Standard Error Messages
Item Description
MessageName1, Name of the standard message as shown in the table previously.
MessageNamen
Text1, Textn Represents the replacement message text
The following example will change the default error message Missing Answer(s) for all questions
within this survey.
);
);
End Metadata
175
Chapter 16 Customizing the Standard Error Messages Survey Program
If a respondent did not choose an answer for any question within the survey, they would see:
Item Description
helperfields Keyword used to store additional information for a field/question
MessageName1, Name of the standard error message.
MessageNamen
Text1, Textn Represents the replacement message text
176
Survey Programming Fundamentals Chapter 16 Customizing the Standard Error Messages
This example will make the respondents error message clearer in its meaning.
DaysTravelYr "On average how many days per year do you travel for business or leisure?"
Example long [0 .. 365]
helperfields (
StandardTexts "StandardTexts" block fields
(
Errors "Errors" block fields
(
NotInRange "{ANSWER} is more than the number of days in a year. Please try
again."
info;
);
);
);
177
Chapter 16 Customizing the Standard Error Messages Survey Program
When the respondents answer is out of the range, it will display a new error message:
178
Survey Programming Fundamentals Chapter 17 Functions & Subroutines
In this chapter we
w will:
n
Define Functions and ubroutines
Lets look at some very basic examples to understand the concept of functions and subroutines.
179
Chapter 17 Functions & Subroutines Survey Programming Fundamentals
Subroutine
To define a subroutine:
Statements
End Sub
Item Description
Sub Marks the start and end of a subroutine
End Sub
Name Represents a unique name given to the subroutine
Statements Represents any statements to be executed within the subroutine
var1, var2, varN Represents the name of variables that are passed to the subroutine from the
point where it is called. The variables together are called the argument list.
parameter1, Represents the actual parameters that are passed to the subroutine. The
parameter2, order of these parameters will match up with the variables on the subroutine
parameter3 (example: parameter1 is the information that will be inserted in the
subroutine represented as var1)
Subroutine Example
Depending on the specific look of your surveys, you may want to control the column widths of a grid at
a default level for all grids, or have individual control. If you need individual control, it would be nice to
have a way to indicate the specifics per grid on a single line in the script. We can create a subroutine
to help us with this.
Suppose you had two grids in your study that after the default styles were applied, they looked like
this:
180
Survey Programming Fundamentals Chapter 17 Functions & Subroutines
Looking at the grids, they might look better with some specific styles applied to them. As we learned in
the style section, you could specify the style for each grid (AirlineRating and InterestinLocation) in the
routing section:
Routing(Web) AirlineRating.Categories[..].Label.Style.Cell.Width =
Example "300px" AirlineRating[0].Item[0].Categories[..].Label.Style.Cell.Width
= "70px" AirlineRating[0].Item[0].Categories[..].Label.Style.Cell.Wrap
= true AirlineRating.Ask()
InterestinLocation.Categories[..].Label.Style.Cell.Width = "120px"
InterestinLocation[0].Item[0].Categories[..].Label.Style.Cell.Width = "90px"
InterestinLocation[0].Item[0].Categories[..].Label.Style.Cell.Wrap = true
InterestinLocation.Ask()
End Routing
181
Chapter 17 Functions & Subroutines Survey Programming Fundamentals
Now we might say that this code could be useful in many studies. As you can see, we are repeating the
same basic text each time, just changing the values of the style properties and the question it applies
to. This repetitiveness makes it a candidate for a subroutine.
First, create the subroutines structure and give it a name that is easily recognizable:
Sub GridStyle1()
End Sub
182
Survey Programming Fundamentals Chapter 17 Functions & Subroutines
Then, ask yourself what will change each time about the lines of code; the question name and the
values of the styles will change each time, so they need to be replaced with a variable to represent
those items:
End Sub
Next, add the code. Beginners may find it helpful to add the code for one question without the
substitutions then make the changes to that code with the parameters.
AirlineRating.Categories[..].Label.Style.Cell.Width = "300px"
AirlineRating[0].Item[0].Categories[..].Label.Style.Cell.Width = "70px"
AirlineRating[0].Item[0].Categories[..].Label.Style.Cell.Wrap = true
End Sub
Looking at the above example we will need to change AirlineRating, 300px, 70px, and true to
match the variable names we defined on the first line of the subroutine:
QuestionName.Categories[..].Label.Style.Cell.Width = ColHeadWid
QuestionName [0].Item[0].Categories[..].Label.Style.Cell.Width = ColWid
QuestionName [0].Item[0].Categories[..].Label.Style.Cell.Wrap = ColWrap
End Sub
183
Chapter 17 Functions & Subroutines Survey Programming Fundamentals
The above subroutine alone does nothing. You need to Call the subroutine and specify the parameter
information for a specific action. Here is the completed subroutine example:
Routing(Web)
Example GridStyle1(AirlineRating,"300px" , "70px" ,true)
AirlineRating.Ask()
End Sub
End Routing
Function
As stated earlier in this chapter, a function differs from a subroutine in that it can pass a value back to
where the call originated. In the syntax below, you will see it is very similar to the subroutine, but now
you may set a value equal to the function name to pass back and use within your script.
Statements
Name = value
End Function
184
Survey Programming Fundamentals Chapter 17 Functions & Subroutines
Item Description
Function Marks the start and end of a function
End Function
Name Represents a unique name given to the function
Statements Represents any statements to be executed within the function
var1, var2, varN Represents the name of variables that are passed to the function from the
point where it is called. The variables together are called the argument list.
Value A value that is returned to the point where the function call occurred
(Optional)
parameter1, Represents the actual parameters that are passed to the function. The order
parameter2, of these parameters will match up with the variables on the function
parameter3 (example: parameter1 is the information that will be inserted in the function
represented as var1)
185
Chapter 17 Functions & Subroutines Survey Programming Fundamentals
AgencyHeardOf "Which of the following travel agencies have you heard of?"
categorical
{
use AgencyLst
};
Routing(Web)
agencyheardof.Style.Columns=3
agencyheardof.Ask()
agencyuse.Categories.Filter=agencyheardof
agencyuse.Ask()
End Routing
And you wanted to force the style of the number of columns for the AgencyUse question to have no
more than 10 categories in each column. Since the categories of the question AgencyUse are
dependent on the response to AgencyHeardOf, we will need to find out the number of categories
chosen in AgencyHeardof, and divide by 10 to see how many columns we need using the AnswerCount
Dimensions Function we learned in
186
Survey Programming Fundamentals Chapter 17 Functions & Subroutines
Basic Routing Logic, page 60. Since dividing our number of responses by 10 may not result in a whole
number, we will also use a builtin function, int(), which returns the integer portion of a number.
Routing(Web)
Example agencyheardof.Style.Columns=3
agencyheardof.Ask()
agencyuse.Categories.Filter=agencyheardof
End Routing
Since this may be an action we would want to do on other questions or in other studies, it might be
advantageous to create a function instead. The function below does just that. It was created in a
similar way to the subroutine.
Routing(Web)
Example agencyheardof.Style.Columns=3
agencyheardof.Ask()
agencyuse.Categories.Filter=agencyheardof
agencyuse.Style.Columns=ForceCols(agencyheardof)
agencyuse.Ask()
Function ForceCols(filterQ)
Dim Actual, IntegerValue, DecimalValue
Actual = CDouble(filterQ.AnswerCount())/10
IntegerValue = int(filterQ.AnswerCount()/10)
DecimalValue = Actual IntegerValue
187
Chapter 17 Functions & Subroutines Survey Programming Fundamentals
You can see that the function is set up very much the same as the subroutine, in that it has a name
(ForceCols) and has a parameter (filterQ). The difference is that after the function is completed, it is
set to a value. The values can be anything.
Exercise
Open the reusable.mdd file. Make the following routing section code more reuseable with the
concepts learned in this chapter. It would be helpful to have a piece of reusable code that would
allow you to easily specify the number of response columns, column width, and question text color for
specific questions.
Routing(Web)
PrimaryTravel.Style.columns = 3
PrimaryTravel.Style.Width = 300
PrimaryTravel.Label.Style.Color= "#0000FF"
PrimaryTravel.Ask()
CountryVisited.Style.Columns=2
CountryVisited.Style.Width = 600
CountryVisited.Label.Style.Color= "#00FF00"
CountryVisited.Ask()
End Routing
188
Survey Programming Fundamentals Chapter 18 Validation
Chapter 18 Validation
In the last chapter we discussed the concepts of subroutines and functions. Dimensions scripting has a
unique function that allows you to easily validate logic in questions. We will also look at additional
concepts that will help us validate the logic of the survey.
In this chapter we
w will:
Validate a text question to follow a pattern
t
Create custom
s logic withh the use of
Dimensions
n validation functions
Validation(" expression");
189
Chapter 18 Validation Survey Programming Fundamentals
Test your expressions thoroughly, as there are many variations to regular expressions, too numerous
to place in this manual. Here are a few to help you understand the examples below.
Symbol Description
\w Matches any word character (az, AZ, 09)
\W Matches any nonword character.
\d Matches any decimal digit. Equivalent to \p{Nd} for Unicode and *09+ for nonUnicode,
ECMAScript behavior.
\D Matches any nondigit. Equivalent to \P{Nd} for Unicode and *^09] for nonUnicode,
ECMAScript behavior.
The following example will check the length of the phone number and also if it follows the specific
pattern with 2 dashes.
Example
Phone "Please enter your 10digit phone number with dashes:"
text [7..20]
validation("\d,3-\d{3}\d{4}");
The regular expression above shows you want 3 decimal digits (numbers) a dash, 3 more numbers a
dash and 4 numbers.
190
Survey Programming Fundamentals Chapter 18 Validation
The next example is more flexible, allowing you to check an email address to ensure it contains an @
sign.
Email "Email:"
Example text [5..100]
helperfields (
StandardTexts "" block fields
(
Errors "" block fields
(
InvalidText "You must enter a valid email address with an @ and period. "
info;
);
);
) validation("[.\w]+\@[.\w+**.\w]+\.*.\w]*");
This expression ensures the respondent answered a dash, period or any word character (az), then a
mandatory @ sign, followed by a dash, period or any word character.
191
Chapter 18 Validation Survey Programming Fundamentals
Statements
functionname = True
Statements
functionname = False
End Function
Item Description
Function Defines the start and end of the function
End Function
functionname Represents the unique name given to the function
Question Parameter that represents the question you are attaching to the function (this
will always be Question)
IOM Parameter for the Interview Object Model (This will always be IOM)
Attempt Parameter for the number of current custom validation attempts (This will
always be Attempt, if used, but it is an optional parameter). Could be used to
set the number of times the function should attempt to receive a True value.
Statements Represents the Dimensions scripting statements to do any action and return a
value, such as check logic
True Values that the Dimensions custom validation function must pass back. These
False special functions must set the functionname to true or false
192
Survey Programming Fundamentals Chapter 18 Validation
To set the validation function to use for a question, use the following statement in the routing section
somewhere prior to asking the question:
Routing(Web)
Name.Validation.Function = functionname
Name.Ask()
End Routing
Item Description
Name Name of the question you wish to validate
Validation.Function Properties to set the validation function for the question.
functionname Represents the unique name given to the function
There are a few things to note about creating custom validation functions:
To reference another metadata item (besides the question you are validating) inside the
function, you need to reference the question with IOM.Questions.QuestionName.
The function must return either a True (logic is correct, move on to the next question) or False
value (logic is not correct, issue an error message if the number of attempts has not been met).
They can only have the parameters Question, IOM, and Attempt. If you want to include more
variable information into the function, one way to achieve this is to add custom properties in
the metadata of the question you wish to validate. (More to come on this subject.)
Name.Errors.AddNew("errorname", errortext.label)
Item Description
Name Name of the question you want to apply an error message to
Errors.AddNew States you want to add a new error to the standard set of error messages
errorname Represents the unique name given to the error message
errortext Represents the info item created to hold the text for the error message. You can
just add text in double quotes in the routing section for this, but it is highly
recommended to make the info item.
label Will show the label of the info item as the error message text
193
Chapter 18 Validation Survey Programming Fundamentals
You define the error message you want to use as an info item in the metadata section. This
is important for multilingual projects because it makes the message text available for
translation.
The example below is a categorical grid that displays a column of numeric boxes to enter information
that should add to 100%.
PercActivity "Thinking of your travel over the last year, what percentage of your time
was spent using the following modes of transportation? The total should add to 100%."
loop
{
use Activities
} fields
(
QPercent "Percentage"
style(
Width = "30px"
)
long [0 .. 100]
initialanswer(0 );
) expand grid;
End Metadata
194
Survey Programming Fundamentals Chapter 18 Validation
In the routing section, we will create the special Dimensions validation function to make sure our grid
adds to 100% as shown below.
Routing(Web)
Example IOM.LayoutTemplate = "Card_Blue_TopAndBottomErrors.htm"
PercActivity.Validation.Function = "ValidateGrid100"
PercActivity.Ask()
Question.Errors.AddNew("ErrorGrid",
IOM.Questions.ErrorGridAddto100.Label)
ValidateGrid100 = False
Else
ValidateGrid100 = True
End If
End If
End Function
End Routing
195
Chapter 18 Validation Survey Programming Fundamentals
Lets change the scenario slightly. What if you wanted to modify the question, so that the question
prior to this was:
Thinking of your travel over the last year, approximately how many hours did you spend using some
type of transportation?
This will involve modifying our previous example to be able to reference that questions response
within the function.
HrsActivity "Thinking of your travel over the last year, how many hours of your time was
spent using the following modes of transportation? The total should add to
{#HrsTravelMode}." loop
{
use Activities
} fields
(
QHours "Hours"
style(
Width = "30px"
)
long [0 .. ]
initialanswer(0 );
) expand grid;
End Metadata
196
Survey Programming Fundamentals Chapter 18 Validation
Again, the routing section is where the validation happens. Notice the reference to the additional
question with the IOM.Questions preceding it.
Routing(Web)
Example
IOM.LayoutTemplate = "Card_Blue_TopAndBottomErrors.htm"
HrsTravelMode.Ask()
HrsActivity.Validation.Function = "ValidateGridEqualDependentQ"
HrsActivity.Ask()
Question.Errors.AddNew("ErrorGrid", IOM.Questions.
ErrorGridAddtohrs.Label)
ValidateGridEqualDependentQ = False
Else
ValidateGridEqualDependentQ = True
End If
End if
End Function
End Routing
197
Chapter 18 Validation Survey Programming Fundamentals
The above works nicely, however it is very specific to the question. The line:
Would have to be changed every time it is used for a different question, which is not a good practice.
As stated above, one of the biggest differences between standard functions and custom validation
functions is that currently you cannot add any additional parameters. This limits the flexibility of
custom validation functions. One way that you could pass parameters into a function to make it more
reusable is by placing custom properties in the metadata.
Item Description
Name Name of the question in the metadata section
"text" Text of the question
[property] Represents any information you want stored in the metadata associated with the
metadata item
type Represents the metadata item type (categorical, long, etc.). Notice the custom
properties are prior to this.
Custom properties are an advanced concept, but an important one to remember as you progress with
your Dimensions Scripting learning. Lets add a custom property to our previous example so that we
do not have to make our function so specific to these sets of questions. Below in bold you will notice
the addition of custom properties that adds the name of the question we want to use in the function
to compare to the sum of our grid.
198
Survey Programming Fundamentals Chapter 18 Validation
HrsActivity "Thinking of your travel over the last year, how many hours of your time was
spent using the following modes of transportation? The total should add to
{#HrsTravelMode}."
[ dependentQ = "HrsTravelMode" ]
loop
{
use Activities
} fields
(
QHours "Hours"
style(
Width = "30px"
)
long [0 .. ]
initialanswer(0 );
) expand grid;
End Metadata
199
Chapter 18 Validation Survey Programming Fundamentals
In the routing you will see the change to the comparison line. Notice the addition of the comments to
identify what is needed for the function.
Routing(Web)
Example
IOM.LayoutTemplate = "Card_Blue_TopAndBottomErrors.htm"
HrsTravelMode.Ask()
HrsActivity.Validation.Function = "ValidateGridEqualDependentQ"
HrsActivity.Ask()
Question.Errors.AddNew("ErrorGrid", IOM.Questions.
ErrorGridAddtohrs.Label)
ValidateGridEqualDependentQ = False
Else
ValidateGridEqualDependentQ = True
End If
End if
End Function
End Routing
Now this function can be reused in different projects. You can see how a library of custom validations
will speed the programming process over time.
200
Survey Programming Fundamentals Chapter 19 Compound Questions
Differences
e between loops
o and compound
o
questions
{ Categories } fields
Question1;
QuestionN;
);
Item Description
CompoundName
n Unique
n name for the compoundo metadata item
"Text" Optional Text to display across the top of the screen of the compound question
compoundn Keyword
e to cr eate a compound metadata item
categories Represents the categories for which the questions and loops are to be asked.
Y u may use a shared list here if you wish.
fields h the compound item
Precedes the questions within
Question1, Categorical questions and categorical loops that you want to display side by side.
QuestionN
201
Chapter 19 Compound Questions Survey Programming Fundamentals
You will notice in the above example that all the questions on the page share a list of airlines. The next
example will show how this can be created as a compound question.
202
Survey Programming Fundamentals Chapter 19 Compound Questions
AirlineQ "Please answer the following questions about the airlines listed." compound
{
use Airlines
} fields
(
FlownBefore "Flown Previously"
Categorical [1..];
Trips6MoLoop "# of Trips Past 6 Months" loop fields
(
trips ""
long [0 .. 400];
) expand grid;
SatisLoop "Overall, how satisfied are you with each Airline?" loop fields
(
RateAirline "RateAirline"
categorical [1..1]
{
VerySatisfied "Very Satisfied",
SomewhatSat "Somewhat Satisfied",
SomewhatDisSat "Somewhat Dissatisfied",
VeryDissatisfied "Very Dissatisfied"
};
) expand grid;
);
End Metadata
Routing(Web)
AirlineQ.Ask()
End Routing
203
Chapter 19 Compound Questions Survey Programming Fundamentals
The questions inside of the compound are missing items you might expect to see. For example the
FlownBefore question has no responses, and the two loops have no iteration elements. This is
because all the questions inside of a compound will make reference to the shared categories from the
first section of the compound.
The compound can be created without omitting these elements, but for the sake of
efficiency you will want to use the method shown above.
AirlineQ "Please answer the following questions about the airlines listed." compound
{ use Airlines
} fields
(
FlownBefore "Flown Previously"
Categorical [1..];
Trips6MoLoop "# of Trips Past 6 Months" loop fields
(
trips ""
long [0 .. 400]
codes(
{
NoAnswer " " NA
} );
) expand grid;
);
204
Survey Programming Fundamentals Chapter 19 Compound Questions
The following validation function creates those logic checks. By referencing the questions inside the
compound by their position (0 = FlownBefore, 1 = Trips6MoLoop), it makes the Function more reusable
for other similar scenarios.
Routing(Web)
Example IOM.LayoutTemplate= "Card_Blue_TopandBottomErrors.htm"
AirlineQ.MustAnswer=False
AirlineQ.Validation.Function="ValidateSimpleCompound"
AirlineQ.Ask()
Function ValidateSimpleCompound(Question,IOM,Attempt)
ValidateSimpleCompound = True
Dim Cat
For Each Cat In Question.Categories
End Function
End Routing
205
Chapter 19 Compound Questions Survey Programming Fundamentals
You cannot drop the similar category lists from the questions in a loop as you can with a
compound
Validation of a compound question is very different that for a grid
206
Survey Programming Fundamentals Chapter 20 Working with Sample
In this chapter we
w will:
n
Retrieve information from the sample table
into the Dimensions Script
Send information
r from the Dimensionss
script to the sample table
Using sample management allows you the option to bring additional information about the
respondents for use during the interview either by:
Displaying information held in the table to the respondent (Hello, Bob. Thank you for
participating.)
Creating a question to hold the sample information so it is easily analyzed with the
respondents answers.
To reference information stored in the sample table about the current respondent:
Item Description
SampleField
i Re presents the name
n of the field in the SQL
Q database that holds th einformation
yo u wish to retrieve.
207
Chapter 20 Working with Sample Survey Programming Fundamentals
Here is an example of pulling information from a sample record into the text of a question. We are
assuming the projects sample table has a field named TAgency that holds the Travel Agencies used
by the people in the sample.
End Metadata
Routing(Web)
VerifyTravelAgent.Label.Inserts["Agency"].Text=IOM.SampleRecord.Item["TAgency"]
VerifyTravelAgent.Ask()
End Routing
If a specific respondents travel agency was Travel Agency XYZ, then their question will appear as
shown below:
208
Survey Programming Fundamentals Chapter 20 Working with Sample
The next example does not display the respondents information, but rather stores it in a question for
analysis purposes.
End Metadata
Routing(Web)
Region.Response.Value = IOM.SampleRecord.Item["SRegion"]
End Routing
You can also put information collected or derived in the script into a sample field.
End Metadata
Routing(Web)
ReceiveTravelInfo.Ask()
IOM.SampleRecord.Item["WantsEmail"] = ReceiveTravelInfo.Response.Value
End Routing
The above example will store a True or False in the sample field, providing you have a sample field
called WantsEmail.
209
Chapter 20 Working with Sample Survey Programming Fundamentals
This is an XML document which mrStudio reads as a sample record by default. The default file is shown
below:
210
Survey Programming Fundamentals Chapter 20 Working with Sample
Item Description
<SampleRecord ID=ID1> Marks the beginning and end of the samplerecord. Can only create
</SampleRecord> a single record for testing within mrStudio.
<Samplefields> Marks the beginning and end of the sample fields for the record.
</SampleFields>
<SampleField> Marks the beginning and end of a sample field.
</SampleField>
<name> Tags to surround the name of the sample field
</name>
<type> Tags to surround the type of field. SQL field types are used. Smallint
</type> = 2; Int = 3; Datetime = 7; Char, Text, Ntext, or NVarchar = 8; Bit = 11
<value> Tags to surround the value you want the sample field to have.
</value>
You have the ability to create your own files and add additional Sample fields as shown below:
211
Chapter 20 Working with Sample Survey Programming Fundamentals
The example below will assume you are using the modified TravelSample.xsu with the additional field
for region.
VerifyTravelAgent "Our records indicate you have used the travel agency {Agency} in the
past, is this correct?"
categorical
{
Yes,
No
};
End Metadata
Routing(Web)
Region.Response.Value = IOM.SampleRecord.Item["SRegion"]
VerifyTravelAgent.Label.Inserts["Agency"].Text=IOM.SampleRecord.Item["TAgency"]
VerifyTravelAgent.Ask()
End Routing
As you can see in the screenshot above, you can easily check your references to sample fields within
the text of your survey (Such as Agency XYZ), but when you are accessing the locals pane, you can also
see that the region has been correctly added to the question, Region.
212
Survey Programming Fundamentals Chapter 20 Working with Sample
In the script:
Routing(Web)
IOM.Language = IOM.Info.User1
End Routing
The above example would set the language to German (DEU) for the interview.
213
Chapter 20 Working with Sample Survey Programming Fundamentals
214
Survey Programming Fundamentals Chapter 21 Working with Quotas
In
n this chapter will cover:
An overview
e of the quota process
Checking and
a changing quotas
q online
The question the quota will be based on scripted in your metadata section.
The targets for the quota.
The type of quota
Lets look at a simple example of making a quota based on the respondents gender.
Targets
Male 500
Gender
Female 500
215
Chapter 21 Working with Quotas Survey Programming Fundamentals
Once you have saved the metadata file, you can create your quota targets by selecting Tools Quotas
or choosing the quota button from the Interview Options toolbar:
You will see the quota tool as shown in the picture below.
On the left of the screen you will see a list of the questions in the survey. Drag and drop the Gender
question onto the quota matrix.
216
Survey Programming Fundamentals Chapter 21 Working with Quotas
We can now see the two gender categories with a grey box to the right of each:
217
Chapter 21 Working with Quotas Survey Programming Fundamentals
Here we can set the target and quota type for the cell.
Type Description
Normal A normal quota will report quota full when the quota count of the completed and
pending interviews is equal to the target.
Allow Over Allow over will report quota full when the quota count of completes is equal to the
target. Note, this does not include the pending and as such you potentially can go over
quota.
Counter A counter quota is really not a quota at all. The system will not stop respondents from
completing interviews once the limit is reached. This type of quota is used for
information purposes only.
Once you have set the target and type for each quota cell we need to name the quota matrix. Well call
this example QuotaGender.
Now Save. This will create a file type with a .mqd extension.
Checking Quotas
Now that we have quota limits defined, we need to add logic to our routing section that tells the
section to check on the quota. Before we do that, lets add an extra item to our metadata. We are
creating a scenario where respondents will be turned away from the survey based on their responses.
Lets add a message to use for informing the respondent what has happened.
End Metadata
In the routing section, we will start by defining a temporary variable to hold our quota check and ask
our quota question.
218
Survey Programming Fundamentals Chapter 21 Working with Quotas
Routing(Web)
Example
Dim Quota_Pend_Result
Gender.Ask()
End Routing
You must make sure that you always check a quota after the respondent has answered.
Routing(Web)
Example
Dim Quota_Pend_Result
Gender.Ask()
Quota_Pend_Result = QuotaEngine.QuotaGroups["QuotaGender"].Pend()
End Routing
As you can see you must reference the name you gave the quota matrix. In this way you can create
multiple quota matrixes and check them at different points of the survey. The temporary variable
Quota_Pend_Result stores the results of the attempted quota pend. Now we need to check those
results and respond accordingly.
219
Chapter 21 Working with Quotas Survey Programming Fundamentals
Routing(Web)
Example
Dim Quota_Pend_Result
Gender.Ask()
Quota_Pend_Result = QuotaEngine.QuotaGroups["QuotaGender"].Pend()
IOM.Texts.InterviewStopped = OverQuota.Label
IOM.Terminate(Signals.sigOverQuota)
End If
End Routing
The If statement is checking to see if the Pend() attempt resulted in the success of one or more quota
cells. If this was not the case, then the respondent has failed the quota check. We will set the
InterviewStopped text to the message we defined in an info item in our metadata section. Then we
terminate the interview, flagging the respondent as over quota.
220
Survey Programming Fundamentals Chapter 21 Working with Quotas
Quotas In mrStudio
If you try running this in mrStudio now, you will get an error message by default. One choice is to skip
over the code when running inside of mrStudio by adding a check for when the script is in Debug
mode.
Routing(Web)
Example
Dim Quota_Pend_Result
Gender.Ask()
Quota_Pend_Result = QuotaEngine.QuotaGroups["QuotaGender"].Pend()
IOM.Texts.InterviewStopped = OverQuota.Label
IOM.Terminate(Signals.sigOverQuota)
End If
End If
End Routing
mrStudio v.4.5 and above does have the capability to simulate quotas. Note you must
have either Microsoft SQL Server 2000 or 2005, including the free SQL Server 2005 Express
Edition and Microsoft SQL Server Desktop Engine (MSDE) to use this feature. See the DDL
for more detail: DDL.chm::/mrstudio_testing_quotas.htm
221
Chapter 21 Working with Quotas Survey Programming Fundamentals
Each quota matrix in your survey will be a button on the left hand side of the activity page:
222
Survey Programming Fundamentals Chapter 21 Working with Quotas
You also may see a dropdown list that allows you to change additional quota information.
Type Description
Do Not Edit View only mode.
Targets Allows you to modify the targets for each quota cell.
All Allows you to modify the target, complete, pending and type for each quota cell.
223
Chapter 21 Working with Quotas Survey Programming Fundamentals
When the Targets option is selected textboxes will appear. You can raise or lower the cell targets. Once
you have entered the new correct targets click the Update button.
224
Survey Programming Fundamentals Chapter 21 Working with Quotas
When the All selection is chosen you can edit the targets, complete count, pending count as well as
change between Normal, OverQuota and Counter quota types.
225
Chapter 21 Working with Quotas Survey Programming Fundamentals
226
Survey Programming Fundamentals Chapter 22 Creating MultiLingual Projects
In this
t chapter we will cover:
An overview e
e of how to execute e in
a survey
multiple languages
a
Once you have a metadata file, you can add the translations through the product, mrTranslate.
mrTranslate reads the metadata file and presents the text of your survey in a format similar to a
spreadsheet. Then you can add additional languages as columns in mrTranslate .
For detailed information on using mrTranslate, see the Users Guide in the DDL:
mrTranslate.chm::/mrtranslate overview.htm
227
Chapter 22 Creating MultiLingual Projects Survey Programming Fundamentals
Then save the metadata file and now it will contain the additional languages. Note that when you re
open the metadata file in mrStudio, you will not see the additional languages within the text of the file,
but they are in the metadata file. To verify additional languages are in the metadata using mrStudio:
228
Survey Programming Fundamentals Chapter 22 Creating MultiLingual Projects
End Metadata
Routing(Web)
LanguageQ.Ask()
IOM.Language = LanguageQ.Categories.[LanguageQ].Name
End Routing
Note that in the example above, the names of the responses (ENU, DEU, ESN) must be the 3digit
Microsoft language codes.
If the script has the translations added, you will be able to see the languages changes within mrStudio
as you run the survey.
To find a full list of the language codes, see the DDL: UserGuide.chm::/Intug
mrscriptmetadata_languages_3char.htm
Routing(Web)
Example
IOM.Language = IOM.SampleRecord.Item["SLanguage"]
End Routing
229
Chapter 22 Creating MultiLingual Projects Survey Programming Fundamentals
If the templates contain text that needs to be translated, use localized templates for each
language so that the proper text is shown.
Verify the ErrorMessage.mdd file has the error messages for the languages you will be using.
Always reference info items in the routing section for any text, such as custom error messages
or text inserts. Text in the routing section is not seen by mrTranslate, only the metadata
section.
230
Survey Programming Fundamentals Chapter 23 Additional information for Analysis
In this
t chapter we will
w cover:
Adding a lternate text forr reporting purposes
r
231
Chapter 23 Additional information for Analysis Survey Programming Fundamentals
You will now see a blank spot by all text in the metadata labeled ANALYSIS:. You can place the
alternate text in double quotes as shown in the picture below:
Factors
If you wish to add statistical elements, such as a mean or standard deviation, to your categorical
questions, then you need to add a multiplier to each response choice. Even if you do not add the
statistical elements, factors can also be helpful to end users of the data creating cross tabulations with
mrTables or mrStudio.
Text Description
factor Keyword to identify you wish to add a multiplier to the response for statistical purposes
value Represents the numeric value you wish to assign to the response for statistics.
232
Survey Programming Fundamentals Chapter 23 Additional information for Analysis
This example shows you how to specify values for each age range for statistics in use with other
Dimensions products, such as mrTables, Desktop Reporter, or mrStudio with tables scripting.
ElementTypes are not seen during interviewing only in analysis, such as using mrTables or
creating cross tabulations with mrStudio. They are a single line of information, such as a
summary item or mean score.
Axis expressions are also not seen during interviewing, but are usually more than a single line
of analysis results. An example would be adding a predetermined range of categories to a long
or double type question for analysis purposes.
233
Chapter 23 Additional information for Analysis Survey Programming Fundamentals
ElementTypes
You use the optional elementtype keyword to create a special element in metadata for use in analysis.
{ID1 "AltText1,
IDn "AltTextn",
};
Item Description
Name Unique identifier for the item within your questionnaire. They must start with a
letter or underscore ( _ ) and contain only alphanumeric characters or the
symbols @, $, #, or _
"Text" Text associated with the item (considered the label in the object model).
Type Identifies the question type (categorical, long, etc.)
ID1, IDn Unique identifying name for the response. This needs to be unique per
question, not metadata file. Rules for the response names are the same as the
name of the question.
AltText1, Optional text to show the respondent instead of the name of the question. This
AltTextn will apply when the name of the question is not the same as the text you wish to
show the respondent.
IDElement Unique identifying name for the special element. Rules for this name are the
same as the name of the question.
AltTextElement Text to represent the special element
elementtype Keyword that indicates you will be specifying using a special element
typevalue Represents the keywords listed in the next table to state the type of special
element you need
Below is a table with a few common analysis elements, represented by type_value in the syntax
example above.
Text Description
AnalysisCategory An element that is used only for analysis. You can use this value for categories
that you do not want to appear in interviews. An example would be creating a
TopBox or BottomBox score.
AnalysisMean An analysis element that is used to show the mean value of a variable.
AnalysisStdDev An analysis element that is used to show the standard deviation of a variable.
AnalysisStdErr An analysis element that is used to show the standard error of a variable.
234
Survey Programming Fundamentals Chapter 23 Additional information for Analysis
To use the types listed, most require additional properties. Here is the previous example where the
mean value has been added to the age question. Notice the additional parameters required for a
mean with categories.
Another helpful element type is the AnalysisCategory. This allows you to create additional elements in
questions that are not seen during the interview, only in analysis. The following define list will provide
you with a Top and Bottom Box Score for each question using the list in the analysis.
235
Chapter 23 Additional information for Analysis Survey Programming Fundamentals
In the previous example the @ represents any question the define is used with. If you wish
to use a combining element directly in a question without a define list, the expression
would be "qname * {VS, SS}"
Axis Expressions
Another way to speed tabulation processes would be to create analysis items called axis expressions.
These can create many different types of analysis items, a common one in interview scripts would be
categorical ranges on numeric questions.
The axis expressions are dynamically created statements attached to the metadata questions. The
syntax is very similar to what you would do in a data management script.
{ID1 "AltText1,
IDn "AltTextn"}
axis ("axis_spec");
Item Description
Name Unique identifier for the item within your questionnaire. They must start with a
letter or underscore ( _ ) and contain only alphanumeric characters or the
symbols @, $, #, or _
"Text" Text associated with the item (considered the label in the object model).
Type Identifies the question type (categorical, long, etc.)
ID1, IDn Unique identifying name for the response. This needs to be unique per
question, not metadata file. Rules for the response names are the same as the
name of the question.
AltText1, Optional text to show the respondent instead of the name of the question. This
AltTextn will apply when the name of the question is not the same as the text you wish to
show the respondent.
axis Keyword to represent elements will be added that will only be seen in analysis
axis_spec Represents many different syntax that creates elements to be seen in analysis
236
Survey Programming Fundamentals Chapter 23 Additional information for Analysis
The following example will collect a long question type during the interview, but easily allow people
doing analysis to view the preset ranges of answers and a mean value.
End Metadata
These items can be added after live data collection, so dont worry if you dont have all the
analysis information up front.
The metadata syntax check will only be looking for syntax mistakes, not if your logic actually
works. Make sure to create test data and have someone check the analysis fields for accuracy.
Summary
This chapter has just introduced the analysis concepts and by no means has shown all the possibilities.
As your knowledge of Dimensions scripting grows, you will see how all parts of Dimensions scripting
(interviewing, data management and tabulation) are connected. That knowledge will allow you to use
the power of Dimensions Scripting to its fullest potential and do some amazing projects. You are now
on the verge of doing great things with this powerful language. Remember to think out of the box and
try new ways to do things, as this language has so many facets and capabilities.
237
Chapter 23 Additional information for Analysis Survey Programming Fundamentals
238