survey programming fundamentals
DESCRIPTION
Really a good guide to learn survey programming fundamentals ..IT's freeTRANSCRIPT
d
Survey Programming Fundamentals
Survey Programming Fundamentals
Copyright © 2007 by Verge Consulting, Inc.
All rights reserved. No part of this work may be reproduced or transmitted in any form or my any means, electronic or mechanical, including photocopying, recording, or by any information storage or retrieval system, without prior written permission of Verge Consulting.
Trademarked names may appear in this book. Rather than use a trademark symbol with every occurrence of a trademark name, we use the names only in an editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the trademark.
For additional information please contact Verge Consulting directly at 4146 Sherel Lane, Cincinnati, OH 45209. Phone 513‐282‐3762, fax 866‐822‐9333 or visit http://www.VergeConsulting.com.
The information in this book is distributed on an “as is” basis, without warranty. Although every precaution has been taken in the preparation of this work, neither the author(s) nor Verge Consulting shall have any liability to any person or entity with respect to any loss or damage caused or alleged to be caused directly or indirectly by the information contained in this work.
Version: SPF12 (Dimensions 4.5)
Survey Programming Fundamentals Table of Contents
I
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
What’s 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
Table of Contents Survey Programming Fundamentals
II
Tips for Creating Metadata ................................................................................................................... 25
Viewing and Testing the Survey in mrStudio ........................................................................................ 26
Exercise ................................................................................................................................................. 28
Chapter 4 Special Responses and Options ............................................................................................ 31
Single Response Choices in Multiple Selection Questions ................................................................... 31
Special Responses with Categorical Questions ..................................................................................... 34
Categorical Responses with Non‐Categorical Questions ...................................................................... 36
Collecting Other Text Responses in Categorical Questions .................................................................. 38
Subheading ........................................................................................................................................... 39
Exercise ................................................................................................................................................. 42
Chapter 5 Basic Routing Logic................................................................................................................ 45
Asking Questions ................................................................................................................................... 47
Read Only Items .................................................................................................................................... 49
Conditional Statements ........................................................................................................................ 50
If… Then… Else .................................................................................................................................. 50
Select Case ............................................................................................................................................ 52
Goto ...................................................................................................................................................... 55
Logical Expressions ............................................................................................................................... 56
Numeric Questions ........................................................................................................................... 56
Boolean Questions ............................................................................................................................ 57
Text Questions .................................................................................................................................. 57
Categorical Questions ....................................................................................................................... 58
Logical Operators .............................................................................................................................. 60
Tips for Routing Section Syntax ............................................................................................................ 62
Adding Error Handling ........................................................................................................................... 63
Exercise ................................................................................................................................................. 64
Chapter 6 Shared Lists ........................................................................................................................... 67
Creating Subheadings with Shared Lists ............................................................................................... 69
Chapter 7 Sorting Categorical Response Lists ....................................................................................... 73
Sorting in Metadata .............................................................................................................................. 74
Routing Section Sorting ........................................................................................................................ 75
Not Sorting Specific Responses ............................................................................................................. 75
Survey Programming Fundamentals Table of Contents
III
Keeping Specific Categories Grouped Together ................................................................................... 77
Exercise ................................................................................................................................................. 78
Chapter 8 Restricting Responses ........................................................................................................... 79
Filter Categories .................................................................................................................................... 79
Limiting Numeric Question Ranges Based on Logic .............................................................................. 86
Exercise ................................................................................................................................................. 88
Chapter 9 Multiple Questions on One Page .......................................................................................... 91
Page....................................................................................................................................................... 92
Block ...................................................................................................................................................... 94
Controlling How Page and Block Questions are Displayed ................................................................... 98
Filtering a Page/Block ....................................................................................................................... 98
Sorting a Page/Block ......................................................................................................................... 99
Exercise ............................................................................................................................................... 100
Chapter 10 Repetitive Questions ‐ Loops & Grids ............................................................................. 101
Categorical Loops/Grids ...................................................................................................................... 102
For Each loops ................................................................................................................................. 106
Categorical Loops with a Numeric Question .................................................................................. 108
Numeric Loops .................................................................................................................................... 111
Exercise ............................................................................................................................................... 114
Chapter 11 Debugging Tools within mrStudio ................................................................................... 115
Auto Answer Questionnaire ............................................................................................................... 115
Producing Test Data ............................................................................................................................ 117
Adding Additional Data Sources ..................................................................................................... 119
Setting Breakpoints ............................................................................................................................. 120
Troubleshooting Specific Sections of Code ......................................................................................... 121
Working with Macros .......................................................................................................................... 123
Updating/Deleting Existing Macros ................................................................................................ 123
Adding Additional Macros .............................................................................................................. 123
Chapter 12 Conditioned Loops and Grids .......................................................................................... 125
Previous Responses Within the Loop ................................................................................................. 125
Loops/Grids Filtered on Previous Responses Outside the Loop/Grid ................................................ 127
Loops/Grids Filtered on Responses to a Different Loop/Grid’s Questions ......................................... 129
Table of Contents Survey Programming Fundamentals
IV
Loops/Grids Filtered on a Sublist of Categories .................................................................................. 131
Exercise ............................................................................................................................................... 134
Chapter 13 Controlling the Look of Your Survey ............................................................................... 137
Overview of the Formatting of a Survey ............................................................................................. 137
Templates ........................................................................................................................................... 137
Applying a Template within Your Script. ........................................................................................ 139
Folders ............................................................................................................................................ 140
Tips for Scriptwriters Regarding Templates .................................................................................... 141
Styles ................................................................................................................................................... 141
Default Styles ...................................................................................................................................... 141
Default ............................................................................................................................................ 142
Categories ....................................................................................................................................... 143
Grid ................................................................................................................................................. 144
Labels .............................................................................................................................................. 146
Navigation ....................................................................................................................................... 146
Questions ........................................................................................................................................ 147
Question Styles ................................................................................................................................... 148
Categorical Questions ..................................................................................................................... 148
Text Questions ................................................................................................................................ 149
Metadata Styles .................................................................................................................................. 150
Custom Controls ................................................................................................................................. 151
XHTML in Labels .................................................................................................................................. 151
What is XHTML? .............................................................................................................................. 151
Final Thoughts on Formatting ............................................................................................................. 152
Exercise ............................................................................................................................................... 153
Chapter 14 Text Substitutions and Text Headings ............................................................................. 155
Displaying Responses to Previous Questions ..................................................................................... 155
Insert Text into the Metadata that will be controlled in the routing section ..................................... 158
Text Headings ...................................................................................................................................... 162
Chapter 15 Enhancing Survey Flow ................................................................................................... 165
Must Answer ....................................................................................................................................... 166
Default Answers .................................................................................................................................. 166
Survey Programming Fundamentals Table of Contents
V
Hidden default responses ............................................................................................................... 169
Initial Response ................................................................................................................................... 170
Exercise ............................................................................................................................................... 172
Chapter 16 Customizing the Standard Error Messages ..................................................................... 173
Global changes to error messages ...................................................................................................... 175
Error messages changes for a specific metadata file .......................................................................... 175
Error messages changes for a specific question ................................................................................. 176
Customizing the error message .......................................................................................................... 177
Chapter 17 Functions & Subroutines ................................................................................................. 179
Definition of Functions and Subroutines ............................................................................................ 179
Subroutine ...................................................................................................................................... 180
Subroutine Example ............................................................................................................................ 180
Function .......................................................................................................................................... 184
Exercise ............................................................................................................................................... 188
Chapter 18 Validation ........................................................................................................................ 189
Validating Text Question Patterns ...................................................................................................... 189
Checking Custom Logic ....................................................................................................................... 192
Adding custom errors ......................................................................................................................... 193
Adding custom properties to metadata ......................................................................................... 198
Chapter 19 Compound Questions ..................................................................................................... 201
Defining Compound Questions ........................................................................................................... 201
Validating a compound question ........................................................................................................ 204
Compound vs. Loop ............................................................................................................................ 206
Chapter 20 Working with Sample ...................................................................................................... 207
Testing sample information within mrStudio ..................................................................................... 209
Alternative to Sample Management to pass information into the survey ......................................... 213
Chapter 21 Working with Quotas ...................................................................................................... 215
Defining Survey Quotas ...................................................................................................................... 215
Checking Quotas ................................................................................................................................. 218
Quotas In mrStudio ......................................................................................................................... 221
Activation with Quotas ....................................................................................................................... 222
Viewing & Changing Quotas ............................................................................................................... 222
Table of Contents Survey Programming Fundamentals
VI
Chapter 22 Creating Multi‐Lingual Projects ....................................................................................... 227
Overview of Translating Studies in Dimensions .................................................................................. 227
Setting the language within the script ................................................................................................ 228
Ask a question to collect and set the language .................................................................................. 228
Set language from a sample field variable .......................................................................................... 229
Tips for creating multi‐lingual projects ............................................................................................... 230
Chapter 23 Additional information for Analysis ................................................................................ 231
Alternate Text for Analysis .................................................................................................................. 231
Adding Analysis Context with mrStudio ......................................................................................... 231
Factors ................................................................................................................................................. 232
Creating Question Items for Analysis.................................................................................................. 233
ElementTypes.................................................................................................................................. 234
Axis Expressions .............................................................................................................................. 236
Tips creating analysis elements .......................................................................................................... 239
Summary ............................................................................................................................................. 239
Survey Pr
ChapteThis courlanguage
The BigThe over
• D
• C
• R
For each
rogramming
er 1 Intrse is designee, specifically
g Picture all process of
Design: Creat
Collect: Colle
Report: Analy
stage there a
T
•mrStu•Build A•mrPap•Autho•mrTra
D
Fundamental
troductiod to provide the task of pr
f running a su
ting the surve
ect the inform
yze the result
are different t
This chap
An overvie
A definitio
An introdumrStudio
dioActivityperrnslate
esign
ls
on to Surva firm foundarogramming s
urvey can be g
ey instrument
mation require
ts and report
tools we can
pter will
ew of the inter
on of Dimensio
uction to docum
•mrI•mrD•mrS
C
Cha
vey Prograation in undesurveys.
grouped into
t and the que
ed of the surv
the findings o
use. For Dime
contain:
view process
ns scripting
mentation and
nterviewDialerScan
Collect
pter 1 Introd
amming rstanding the
three main c
estions associ
vey instrumen
of the resear
ensions this c
:
d
t•S•R•m•m•C
duction to Sur
e Dimensions
ategories.
ated with it
nt
ch
could look like
SPSSReportermrTablesmrStudioClementine
Repo
rvey Program
Scripting
e…
rt
mming
1
Chapter 1 Introduction to Survey Programming Survey Programming Fundamentals
2
What is Survey Design About? Here are some of the tasks involved in survey design:
• Creating a quality survey instrument • Programming survey content and logic • Survey testing (Quality control) • Transferring the project to data collection servers (Activation) • Survey translation • Sample integration • Defining quotas
The Survey Process The historic process for the survey process has at times been tedious. There are a lot of repetitive tasks that take time and money. Dimensions is changing that paradigm. Dimensions scripting allows users to incorporate more automation and reusable code in the process. Dimensions scripting is one unified language for survey design, collection and reporting, so there is less repetition and a more streamlined process.
Dimensions Scripting Overview When working in mrStudio we will be using Dimensions Scripting. There are two languages in Dimensions scripting.
Language Description mrScriptBasic A programming language that is based on Microsoft VBScript.
mrScriptMetadata Proprietary Dimensions syntax used to define survey questions/ metadata.
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.
Interview Object Model The Interview Object Model, typically referred to as IOM, is the foundation of survey programming in Dimensions. IOM defines, for Dimensions, what the components of a survey are and what actions we can take with each component.
Survey Programming Fundamentals Chapter 1 Introduction to Survey Programming
3
Object Oriented Programming When programming a survey in Dimensions you will be using object oriented programming (OOP).
What is Object Oriented 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 doesn’t, this concept will make more sense as you continue your learning.)
Dimensions Development Library Overview Commonly referred to as the DDL, the Dimensions Development Library is a collection of resources. It consists of extensive technical documentation as well as a wide variety of example code.
Chapter 1 Introduction to Survey Programming Survey Programming Fundamentals
4
You can access the DDL through the Help ‐ Contents menu choice in mrStudio, or through:
Start – Programs – SPSS Dimensions – Dimensions Development Library – Documentation 4.5
Navigating the DDL There are many different ways to navigate around the DDL.
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 full‐text 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.
For this course, a good place to start is in the Contents tab:
mrStudio – Interview Scripting – Getting Started
Examples When you installed the DDL you also installed many examples files. The default path for these examples is:
C:\Program Files\SPSS Dimensions\DDL\
Specifically for survey programming you should be aware of:
C:\Program Files\SPSS Dimensions\DDL\Scripts\Interview
These example projects will prove very valuable to give you new ideas for programming.
Survey Programming Fundamentals Chapter 1 Introduction to Survey Programming
5
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
To use a link, right click on the title bar in the DDL:
Select the Jump to URL… menu item.
Chapter 1 Introduction to Survey Programming Survey Programming Fundamentals
6
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.
Survey Programming Fundamentals Chapter 1 Introduction to Survey Programming
7
Since you will be using mrStudio throughout this course, let’s 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.
Interview Options: routing context options, activation, quotas, and metadata tools.
You will get to see many features of mrStudio as you move through this training.
What’s 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.
Chapter 1 Introduction to Survey Programming Survey Programming Fundamentals
8
Survey Pr
ChapteThe core within m
MetadaMetadata
N
Item Name
"Text" Type
Paramet
Semicolo
The next
rogramming
er 2 Coof a survey isrStudio.
ata Items Fa items follow
Name "Text"
DesUnilettsymTexIdeetc
ers Theto a
on Bet
sections cove
Fundamental
nstructins the question
Format w a distinct pa
type parame
scription ique identifieter or underscmbols @, $, #,xt associated wntifies the ite.) ese are optiona question. tween each it
er many of th
In this c
Create ba
Create a m
View and
ls
ng Questions. In this ch
attern you wi
eters;
r for the itemcore ( _ ) and , or _ with the itemem for its func
nal and vary b
em in the me
he different ty
hapter w
asic questions
metadata file
test a survey
ons apter, we wil
ill see as we c
m within your contain only
m (consideredctionality (cat
by item type.
etadata sectio
ypes of quest
we will:
s
e in mrStudio
y within mrSt
Cha
l build our kn
complete this
questionnairy alpha‐nume
the label in ttegorical que
An example
on there is a s
tions.
udio
apter 2 Const
nowledge of c
s chapter:
re. They musric characters
the object mostions, text o
would be the
semicolon.
tructing Ques
creating ques
t start with a s or the
odel). only items,
e responses
stions
9
tions
Chapter 2
10
Example
InformTo createquestion
N
Item Name
"Text" info Semicolo
The intro
2 Constructin
mation Iteme an opening s, you need t
Name "Text"
DesUnilettsymTexKey
on Bet
Intro "unders
info;
oduction will d
ng Questions
ms page with ano create an in
info;
scription ique identifieter or underscmbols @, $, #,xt associated wyword to creatween each it
"Please particstand the trav
display in mrI
introductionnformation it
r for the itemcore ( _ ) and , or _ with the itemate a text‐onlyem in the me
cipate in our rvel needs of c
Interview like
n or have a paem. The synt
m within your contain only
m (consideredy item. This ietadata sectio
research abouconsumers."
e this:
Surve
age with graptax is as follow
questionnairy alpha‐nume
the label in ts the default on there is a s
ut travel. You
ey Programm
hics or openiws:
re. They musric characters
the object motype if it is nosemicolon.
ur answers w
ming Fundame
ng text witho
t start with a s or the
odel). ot specified.
will help us to
entals
out
better
Survey Programming Fundamentals Chapter 2 Constructing Questions
11
Example
Numeric Questions To collect numeric data from your respondents, use one of the following item types:
Name "Text" long [min..max];
Name "Text" double [min..max];
Item Description Name Unique identifier for the item within your questionnaire. They must start with a
letter or underscore ( _ ) and contain only alpha‐numeric characters or the symbols @, $, #, or _.
"Text" Text associated with the item (considered the label in the object model). long Whole‐numbers only (no decimals). The range is from ‐2,147,483,648 to
2,147,483,647. double Decimal numbers. 64‐bit floating point number with at least 15 digits of
precision, in the range ‐1.79769313486232E308 to ‐4.94065645841247E‐324 for negative values; 4.94065645841247E‐324 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?"
long [0 .. 365];
AmtSpentAccom "What price did you pay for your last overnight accommodations?"
double [0 .. 3999.99];
Chapter 2 Constructing Questions Survey Programming Fundamentals
12
The browser will display a box and the respondent can fill in amounts of their choice, as shown below:
Minimum and Maximum Parameter Options When specifying the minimum and maximums for numeric questions, [min..max], you have many options to collect the numeric data necessary.
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] [1..10,50..100]
Commas denote single values or breaking ranges.
Text Questions When you want to create a question that collects any type of text information, use a text type.
Name "Text" text [min..max];
Item Description Name Unique identifier for the item within your questionnaire. They must start with a
letter or underscore ( _ ) and contain only alpha‐numeric 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.
Here is a simple example of an open ended question.
Survey Programming Fundamentals Chapter 2 Constructing Questions
13
Example
BestVacation "Please tell us about your best vacation experience."
text [1..];
Will display like the picture below:
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.
Chapter 2 Constructing Questions Survey Programming Fundamentals
14
Categorical To create a question which offers a list of options to choose from is considered a categorical type question.
Name "Text" categorical [min..max]
{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 alpha‐numeric 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, AltTextn
Optional text to show the respondent instead of the name of the question. This will apply when the name of the question is not the same as the text you wish to show the respondent.
Parameter Options Restricting the Number of Responses to be Chosen As stated above, the minimum and maximum options provide the number of responses that can be answered for a specific question. There are some variations in syntax to consider.
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)
Survey Programming Fundamentals Chapter 2 Constructing Questions
15
Example
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 on a leisure trip?"
categorical [1..1]
{
Camera,
Map,
ComfortableFootwear "Comfortable Footwear",
FriendTravelCompanion "Friend/Travel Companion"
};
Creates a single categorical question with radio buttons:
Chapter 2 Constructing Questions Survey Programming Fundamentals
16
Example
CountryVisited "Which of the following countries have you visited?"
categorical [1..]
{
Antarctica,
Africa,
Asia,
Australia,
Europe,
NorthAmerica "North America" ,
SouthAmerica "South America"
};
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..].
Survey Programming Fundamentals Chapter 2 Constructing Questions
17
Date When requesting a date from the respondent, it is easier to collect a date type versus multiple long type fields.
Name "Text" date ["min".."max"];
Item Description Name Unique identifier for the item within your questionnaire. They must start with a
letter or underscore ( _ ) and contain only alpha‐numeric 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.
Key points regarding dates:
• The format for the date is very flexible. Some (not all) of the formats taken are: o DD‐MonthName‐YYY (7 – April – 2007) o DD‐ShortMonthName‐YYY (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 12‐hour or 24‐hour format; for example, 2:30pm or 14:30. If you do not specify AM or PM, it will assume a 24‐hour 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.
Chapter 2 Constructing Questions Survey Programming Fundamentals
18
Example
LastTripDate "What was the date you left for your last trip?"
date;
TimeforTravel "What time of day do you prefer to travel in the morning?"
date ["1:00am" .. "11:59am"];
The result of the LastTrip date question would look like this:
Survey Programming Fundamentals Chapter 2 Constructing Questions
19
Example
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.
Name "Text" boolean;
Item Description Name Unique identifier for the item within your questionnaire. They must start with a
letter or underscore ( _ ) and contain only alpha‐numeric 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."
boolean;
Chapter 2 Constructing Questions Survey Programming Fundamentals
20
Survey Pr
ChapteNow thattest our s
OpeninYou will f
Start – P
rogramming
er 3 Cret you know hoscript. We wi
ng mrStudfind mrStudio
Programs – SP
T
Fundamental
eating anow to create ill use mrStud
dio o at:
PSS Dimensio
This cha
How to cre
Overview omenus
How to tes
ls
n mrStudiosome basic qdio to create t
ons – mrStud
apter wil
eate an mrStud
of mrStudio an
st your survey
Chap
o Interviequestion typethe Dimensio
io.
l cover:
dio metadata f
nd the toolbars
with mrStudio
pter 3 Creatin
ew Script s, let’s start uon Scripting fo
file
s and
o
ng an mrStud
t using mrStudior our survey
io Interview S
io to create as.
Script
21
nd
Chapter 3 Creating an mrStudio Interview Script Survey Programming Fundamentals
22
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 don’t want to go back to the DDL or manual for syntax questions.
Survey Programming Fundamentals Chapter 3 Creating an mrStudio Interview Script
23
Overview of Toolbars/Shortcuts mrStudio has many tools to help you with the creation of your script. Let’s review the different toolbars and parts of the mrStudio screen.
Formatting Toolbars The formatting toolbars provide basic but needed editing skills in mrStudio.
File Toolbar: Used to create, open save and print files.
Edit Toolbar: Cut, copy, paste, undo, redo and find.
Formatting Toolbar: Indentations, commenting, macros and options.
• 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 pre‐defined 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.
Chapter 3 Creating an mrStudio Interview Script Survey Programming Fundamentals
24
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, let’s 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.
Survey Programming Fundamentals Chapter 3 Creating an mrStudio Interview Script
25
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.
Interview Options Toolbar The Interview Options toolbar gives you access to mrStudio tasks.
From left to right the options are:
• Adding routing contexts
• Removing routing contexts
• Metadata tool1
• Metadata tool2
• HTML tidy (tries to improve your HTML code in your templates to be perfectly formed)
• Creating quotas (opens the Quota Tool Application)
• Activation of the survey to mrInterview
Tips for Creating Metadata We will discuss the mrStudio environment and the tools provided to help you create your scripts throughout the manual. Here are a few tips to get you started:
• 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.
Chapter 3 Creating an mrStudio Interview Script Survey Programming Fundamentals
26
• After saving and closing the document, mrStudio reformats your metadata into a standardized format. The term used for this is re‐hydration. Be aware of this so you don’t spend additional time on proper formatting in the metadata section.
Viewing and Testing the Survey in mrStudio When you have saved so that you know all errors are gone, you are ready to view the results of your script. Click the start button on the toolbar:
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.
Survey Programming Fundamentals Chapter 3 Creating an mrStudio Interview Script
27
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 auto‐answering questions with F5. Others, such as creating macros and viewing the locals pane information will come later in your learning.
Chapter 3 Creating an mrStudio Interview Script Survey Programming Fundamentals
28
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 Winn‐Dixie
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
Survey Programming Fundamentals Chapter 3 Creating an mrStudio Interview Script
29
ItemsBought How many items did you buy?
GroceryCost Exactly how much did you spend?
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.
Chapter 3 Creating an mrStudio Interview Script Survey Programming Fundamentals
30
Survey Pr
ChapteIn Chaptechapter a
Single With muchosen inthat the r
N
{
I
rogramming
er 4 Sper 2 we coverand add addit
Responseltiple selection combinationresponse sho
Name "Text "
{ID1 "AltText1
IDn "AltTextn
In t
Fundamental
ecial Respred basic quetional options
Choices inon categoricaln with any otould be a sing
" categorical [
1",
n" exclusive }
this chap
Special keyfunctional
Collecting responden
Creating suappearanc
ls
ponses anstion syntax. s to enhance
n Multiplel questions, yther responsele‐select choi
[min..max]
};
pter we w
ywords to provity
specific text rent chooses oth
ubheadings to ce of categoric
nd Option This chapterthose questio
e Selectionyou may wante. In order foice using the
will cove
vide additional
esponses whener
improve the al questions
Chapter 4
ns r will expand on types.
n Questiont to have certr that logic tokeyword, exc
er:
l
n
Special Respo
on the conce
ns tain responseo happen, youclusive.
onses and Op
epts of that
s that cannotu must indica
ptions
31
t be te
Chapter 4 Special Responses and Options Survey Programming Fundamentals
32
Example
Item Description Name Unique identifier for the item within your questionnaire. They must start with a
letter or underscore ( _ ) and contain only alpha‐numeric 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, AltTextn
Optional text to show the respondent instead of the name of the question. This 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?"
categorical [1..]
{
American,
Delta,
United,
OtherAirline "Other airline",
NeverFlown "Never flown before" exclusive
};
Survey Programming Fundamentals Chapter 4 Special Responses and Options
33
If the respondent tries to choose the response “Never flown before” and any other response, the following error will appear:
Exclusive responses show up in bold by default. This can be overwritten by templates or styles, which will be discussed in Chapter 13 .
Chapter 4 Special Responses and Options Survey Programming Fundamentals
34
Special Responses with Categorical Questions There are special keywords which represent some common responses to interviews, No Answer, Don’t Know, and Refused to Answer.
Name "Text" categorical
{ID1 "AltText1",
ID2 "AltText2" ,
IDn "AltTextn" Keyword};
Item Description Name Unique identifier for the item within your questionnaire. They must start with a
letter or underscore ( _ ) and contain only alpha‐numeric 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, AltText2, AltTextn
Optional text to show the respondent instead of the name of the question. This 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 (Don’t Know), or REF (Refused)
Benefits for using these keywords:
• 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.
Survey Programming Fundamentals Chapter 4 Special Responses and Options
35
Example
HotelChainStayed "Choose the hotel chains you have stayed at this past year."
categorical [1..]
{
InterContinental,
Cendant,
Marriott,
Accor,
Choice,
Hilton,
DontKnow "Don’t Remember" DK,
Refused "Prefer not to Answer" REF
};
You can use the keywords as the names for the responses; however after re‐hydration the names will show as a dash (‐).
Chapter 4 Special Responses and Options Survey Programming Fundamentals
36
Categorical Responses with NonCategorical Questions You can add categorical responses to question types that are numeric, text, or date. The special keyword options of NA, DK and REF are typically used in this scenario, as this can prove valuable to provide respondents with a way to indicate they don’t know or prefer not to answer the question.
Name "Text" qtype [min..max]
codes (
{ID1 "AltText1" Keyword,
IDn "AltTextn" Keyword}
);
Item Description Name Unique identifier for the item within your questionnaire. They must start with a
letter or underscore ( _ ) and contain only alpha‐numeric characters or the symbols @, $, #, or _
"Text" Text associated with the item (considered the label in the object model). Qtype Represents the non‐categorical 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, AltTextn
Optional text to show the respondent instead of the name of the question. This 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 (Don’t Know), or REF (Refused). This keyword is optional.
Survey Programming Fundamentals Chapter 4 Special Responses and Options
37
Example
AmtSpentYr "What price did you pay for your last airline flight?"
double [0 .. 3999.99]
codes (
{
dontknow "Don’t remember" DK,
Refused "Prefer not to answer" REF
}
);
This code would create checkboxes below the numeric response box as shown below:
Chapter 4 Special Responses and Options Survey Programming Fundamentals
38
Example
Collecting Other Text Responses in Categorical Questions The other keyword allows the respondent to enter an answer that is not on the category list.
Name "Text" categorical
{ID1 "AltText1",
IDn "AltTextn" other};
Item Description Name Unique identifier for the item within your questionnaire. They must start with a
letter or underscore ( _ ) and contain only alpha‐numeric 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, AltText2
Optional text to show the respondent instead of the name of the question. This 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."
categorical [1..]
{ InterContinental ,
Cendant,
Marriott,
Accor,
Choice,
Hilton,
OtherHotel "Other Hotel Chain" other,
DontKnow "Don’t Remember" DK,
Refused "Prefer not to Answer" REF };
Survey Programming Fundamentals Chapter 4 Special Responses and Options
39
This will create a text box to collect the specific name of any hotel chains not listed.
You can have multiple other specify responses per question.
Subheading You can create text‐only items to describe a group of responses by creating subheadings.
Name "Text" categorical { Subhead1 "SubText1"
{ ID1 "AltText1", ID2 "AltText2" }, Subheadn "SubTextn" { ID3 "AltText3", IDn "AltTextn" } };
Chapter 4 Special Responses and Options Survey Programming Fundamentals
40
Example
Item Description Name Unique identifier for the item within your questionnaire. They must start with a
letter or underscore ( _ ) and contain only alpha‐numeric 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, Subheadn
Name for Subheading item
SubheadText1, SubheadTextn
Represents alternate text for the Subheadings.
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, AltText2, AltTextn
Optional text to show the respondent instead of the name of the question. This will apply when the name of the question is not the same as the text you wish to show the respondent.
TravelHelp "Have you used any of the following to help you with your travel arrangements?" categorical [1..] { TravelBooks "Travel Books" { LonelyPlanetBook "Lonely Planet", Fodor "Fodor's", Frommer "Frommer's" }, Websites "Websites" { Expedia "Expedia" , Orbitz "Orbitz" , Govt "Government Websites" } };
Survey Programming Fundamentals Chapter 4 Special Responses and Options
41
The previous code will create the following question in the browser:
Chapter 4 Special Responses and Options Survey Programming Fundamentals
42
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 Winn‐Dixie 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 Non‐Prepared 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 Don’t Remember
Survey Programming Fundamentals Chapter 4 Special Responses and Options
43
ItemsBought How many items did you buy?
GroceryCost Exactly how much did you spend?
Prefer not to Answer
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.
Chapter 4 Special Responses and Options Survey Programming Fundamentals
44
Survey Pr
ChapteSo far, wcontrol th
Here are
• C
• T
• A
• A
To access
rogramming
er 5 Bae have only che flow of the
some of the
Control what
The order of q
Add condition
Allows a singl
s the routing
Fundamental
asic Routincreated the me survey ques
many things
questions are
questions
nal statement
e metadata fi
section, click
This ch
Understancontext
Changing
Adding sk
Understanwith logic
ls
ng Logic metadata portstions.
the routing s
e asked
ts about ques
ile with differ
k on the Web
hapter co
nding, adding, re
the order of you
ip logic/routing
nding Dimensionstatements
tion of our su
ection allows
stions to cont
rent routings
tab in your .m
overs:
emoving routing
ur questions
to your survey
ns Functions and
rvey. This ch
s you to do:
trol if/how the
for ease of ch
mdd file as sh
g
use
Chapter 5 B
apter focuses
ey are asked
hanges to mu
hown below:
Basic Routing
s on how to
ulti‐mode surv
Logic
45
veys
Chapter 5 Basic Routing Logic Survey Programming Fundamentals
46
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 mrInterivew’s Build activity or the accessory Word Capture, as they create a paper routing that is read only.
To add an additional routing:
• Tools
• Add Routing Context
Survey Programming Fundamentals Chapter 5 Basic Routing Logic
47
You will be prompted for a name for the routing.
To remove a routing context, click on the tab of the context you wish to remove and choose
Tools ‐ Remove Routing Context as seen in the diagram above.
When setting up your routing, here are a few things to remember:
• There is no re‐hydration 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,
• View the Metadata Explorer
• Click on the Fields folder
• Right‐click to choose “Copy as Ask”
• Paste in the routing section
Chapter 5 Basic Routing Logic Survey Programming Fundamentals
48
By expanding the Fields folder, you can pick and choose specific questions to copy as .Ask statements.
Survey Programming Fundamentals Chapter 5 Basic Routing Logic
49
Read Only Items There is a way to show the question and current response for a question without the ability to change the response:
Name.Show()
Item Description Name Metadata item name .Show() Displays the question and its current response in read‐only 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.
Chapter 5 Basic Routing Logic Survey Programming Fundamentals
50
Conditional Statements Now that we have asked all the questions, let’s 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
For simple conditions it can all be stated on a single line:
If condition Then Action
Additionally, you could add the options for Else if and/or Else:
If condition Then
Actions
ElseIf condition Then
Actions
Else
Actions
End If
Survey Programming Fundamentals Chapter 5 Basic Routing Logic
51
Example
Now let’s 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.
Name.Response.Value = condition or response
Item Description Name Represents the metadata item name .Response.Value Property to reference the named question’s current response value Condition or response
Any condition to represent a possible response for the named question, or specify an actual response
In the next example, we have the following questions as shown in the metadata:
Metadata (en‐US, Question, Label)
TravelItem "From the list below, which one item would you most want to bring with you on a leisure trip?" categorical [1..1] { Camera, Map, ComfortableFootwear "Comfortable Footwear" , FriendTravelCompanion "Friend/Travel Companion" }; 'If Friend/Travel Companion is chosen in TravelItem, ask FriendRelate FriendRelate "What is the relationship of that person to you?" text; 'If Camera is chosen in TravelItem, ask TravelItemCost TravelItemCost "How much would you expect to pay for the camera?" Double [0..5000]; End Metadata
Chapter 5 Basic Routing Logic Survey Programming Fundamentals
52
Example
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)
TravelItem.Ask()
If TravelItem.Response.Value = {FriendTravelCompanion} Then
FriendRelate.Ask()
End If
If TravelItem.Response.Value = {Camera} Then
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).
Select Case Name.Response.Value
Case Response1
Actions1
Case ResponseN
ActionsN
...
[Case Else
ActionsN]
End Select
Survey Programming Fundamentals Chapter 5 Basic Routing Logic
53
Example
Item Description Select Case End Select
Marks the Start and end of the select case statement
Name.Response.Value Question and its response that you are testing Case Response1, Case Response2
Represents responses to a question or expressions that group responses to the question.
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 ActionsN
Represents one or more statements to be executed for respondents who fail 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.
Metadata (en‐US, Question, Label) TravelItem "From the list below, which one item would you most want to bring with you on a leisure trip?" categorical [1..1] { Camera, Map, Comfortablefootwear "Comfortable Footwear", FriendTravelCompanion "Friend/Travel Companion" }; 'If Friend/Travel Companion is chosen in TravelItem, ask FriendRelate FriendRelate "What is the relationship of that person to you?" text; 'If Camera is chosen in TravelItem, ask TravelItemCost TravelItemCost "How much would you expect to pay for that item? " Double [0..5000]; End Metadata
Chapter 5 Basic Routing Logic Survey Programming Fundamentals
54
Routing(Web)
TravelItem.Ask()
Select Case TravelItem.Response.Value
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 question’s categories folder and right‐click to choose Copy as Select statement. You can then paste a shell of the select statement with the question’s categories as a starting point.
Survey Programming Fundamentals Chapter 5 Basic Routing Logic
55
Example
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)
TravelforBusiness.Ask()
If TravelforBusiness.Response.Value = {No} then goto PleasureSection
DaysPerYrBusinessTravel.Ask()
InternationalBusiness.Ask()
PleasureSection:
TravelforPleasure.Ask()
…
End Routing
Chapter 5 Basic Routing Logic Survey Programming Fundamentals
56
Example
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
Metadata(en‐US, Question, Label) AmtSpentAccom "What price did you pay for your last overnight accommodations?" double [0 .. 3999.99]; 'If AmtSpentAccom is $150 or greater, ask TypeAccom question TypeAccom "At what type of accommodations did you stay?" categorical [1..1] { Hotel, Motel, BedBreakfast "Bed and Breakfast", Hostels, Resorts, OtherAccom "Other Accommodations" other}; End Metadata Routing(Web) AmtSpentAccom.Ask() If AmtSpentAccom.Response.Value >= 150 Then TypeAccom.Ask() End If End Routing
Survey Programming Fundamentals Chapter 5 Basic Routing Logic
57
Example
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 alpha‐numeric 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:
Name Like "pattern"
Item Description Name Unique identifier for the item within your questionnaire. They must start with a
letter or underscore ( _ ) and contain only alpha‐numeric 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.
Metadata(en‐US, Question, Label) BestAirTravel "Explain your best experience with air travel. Please mention your destinations, airports and airline." text; 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
Chapter 5 Basic Routing Logic Survey Programming Fundamentals
58
Example
Categorical Questions For single‐response categorical questions, you may find simple expressions to suffice, such as Name.Response.Value={Yes} . However, things will get complex, and you’ll 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.
For a full list of functions, see DDL.chm::/funclib_overview.htm
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.
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.
Survey Programming Fundamentals Chapter 5 Basic Routing Logic
59
Example
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.
CountryVisited.ContainsAny({NorthAmerica,SouthAmerica})
The above statement would be true for respondents choosing North America, South America, or both.
Chapter 5 Basic Routing Logic Survey Programming Fundamentals
60
Example
Example
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.
If CountryVisited.AnswerCount() > 3 then
WhySoMany.Ask()
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 follow‐up 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. It’s recommended to enclose the item to negate in parenthesis as shown below.
Not (TravelHelp.ContainsAny({Expedia}))
The above would be true if the respondent did not answer Expedia for the TravelHelp question.
Survey Programming Fundamentals Chapter 5 Basic Routing Logic
61
Example
Example
Example
AND
Returns true when both parts of the expression are true.
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.
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.
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.
Chapter 5 Basic Routing Logic Survey Programming Fundamentals
62
Example
Some find xor confusing, but it can save some syntax. The following statement is the equivalent of the previous xor statement:
(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 non‐categorical question, you need to refer to it as QuestionName.Response.Coded = {ID}, where ID is the ID of the special response.
Tips for Routing Section Syntax There are numerous ways to write the syntax within the routing section. Here are some hints to help you to take full use of the ScriptAssist within mrStudio.
• Ctrl‐Q to see the full list of questions in your metadata
• Ctrl‐R will display the responses for a Question listed
• Right‐click on a question name in the routing section and choose Goto Definition which will take you to that question in the metadata section
• Choose the period (.) to see valid choices for your statement
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.
Survey Programming Fundamentals Chapter 5 Basic Routing Logic
63
Example
Adding Error Handling Another important aspect of the routing section is the ability to send error messages to both the respondent and the mrInterview logging when there is a problem with the script. Error handling allows the system to gracefully handle errors that occur, as opposed to a generic error messages that will not provide appropriate information to fix the problem and possibly confuse respondents. The code can be standardized and placed in every script. Below is a simple example to use as a starting point.
Routing(Web) '‐‐‐ 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
Breaking down the example above:
• 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.
Chapter 5 Basic Routing Logic Survey Programming Fundamentals
64
Exercise Use the metadata file, Routing.mdd as your starting point. Complete the routing section and routing/skip patterns shown below.
CookAtHome Do you ever cook food at home?
Yes No (Skip to ItemsOwned)
CookMealWk How many meals per week do you cook at home? __________
PeopleCookFor Do you normally cook for any of the following at your home? Check all that apply.
Spouse/Other Adults in the household Children in the household Non‐Household Member Adults Non‐Household Member Children Only for Myself
(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 Non‐Household Member Children, ask AllergyKids)
AllergyKids Do any of the children you make meals for have food allergies?
Yes No
Survey Programming Fundamentals Chapter 5 Basic Routing Logic
65
PrepTime On average, how much time do you devote to preparing a single meal?
30 minutes or less 31‐90 minutes Over 90 minutes Don’t know
(If PrepTime is 30 minutes or less, ask MealStrategy)
MealStrategy Please list some of your strategies for preparing meals so quickly.
(If PrepTime is 31‐90 minutes, ask AmtPrep)
AmtPrep Do you feel that your preparation time for meals is…
Too short Too long Just right Don’t Know
(If PrepTime is Over 90 minutes, ask PrepDescrip)
PrepDescrip Do you take over 90 minutes to prepare meals mainly because of…
The amount of entrees created The complexity of the dishes The number of interruptions during the process Other (specify) ______________ Don’t Know
Chapter 5 Basic Routing Logic Survey Programming Fundamentals
66
ItemsOwned Which of the following kitchenware items do you own?
Bread Maker Food Processor Stand Mixer Wok Fondue Pot None of These
(If respondent owns 3 or more kitchen items in ItemsOwned, ask UseItems)
UseItems Do you use some/all the items mentioned previously…
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.
Survey Pr
ChapteWhen crelist will ato be maquestion
Creating
L
{
I
Item ListName
"Text" Define { } ID1, IDn
AltText1,AltTextn
rogramming
er 6 Sheating a survellow you to crde to your res at once.
a shared list
ListName "T
{ID1 "AltText1
Dn "AltTextn
Dese Uni
lettsymOptKeyIndUniquenam
, Optwillsho
Fundamental
ared Listsey, you may rreate the respesponse list, y
is very simila
ext" define
1",
n" } ;
scription ique identifieter or underscmbols @, $, #,tional text whyword to creaicates the staique identifyiestion, not meme of the quetional text to l apply when ow the respon
This ch
Creating a
Including s
Dealing wior more lis
ls
s repeat the saponse list oncyou have one
r to adding ca
r for the sharcore ( _ ) and , or _ hen list is useate a shared liart of the cateng name for tetadata file. estion. show the resthe name of ndent.
hapter co
re‐useable res
subheadings in
ith identical rests
me responsesce and use it central locat
ategories to a
red list in the contain only
d as a sublistist egories for ththe responseRules for the
spondent instthe question
overs:
sponse list
n a list
sponse text in
s question aftmany times.ion to make t
a categorical q
metadata. Ty alpha‐nume
.
e define list. This needs response na
tead of the nais not the sam
two
Chap
ter question. In addition, ithe changes t
question.
They must staric characters
to be uniquemes are the s
ame of the qume as the tex
pter 6 Shared
Using a sharif changes neto update ma
rt with a s or the
per same as the
uestion. This xt you wish to
d Lists
67
red ed ny
o
Chapter 6 Shared Lists Survey Programming Fundamentals
68
Example
To make use of the responses in a question:
Name "Text" categorical [Min..Max]
{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 { 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 };
Some things to keep in mind about shared lists:
• 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
Survey Programming Fundamentals Chapter 6 Shared Lists
69
Creating Subheadings with Shared Lists You learned to create subheadings in a previous chapter. Now that you have learned shared lists, there is another way to create subheadings using multiple shared lists.
Name "Text" categorical [min..max]
{use listname1 Sublist "Sublistname1",
Use listnameN Sublist "SublistnameN" } ;
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, listnameN
Represents the name of the define lists to use for the sublist categories of the question.
Sublist Keyword to designate the preceding define list as a subheading list “Sublistname1”, “SublistnameN”
Optional Text to display as the subheading Text. If not specified, will use label specified in the define list.
Chapter 6 Shared Lists Survey Programming Fundamentals
70
Example
The following example uses the concept of sublist using two define lists to create subheadings in the categorical question.
Metadata (en‐US, Question, Label) ResortTypes "" define { Historical, AmusementPark "Amusement Park", Beach , Adventure }; CampingTypes "" define { GovtPark "Government Park", RainForest "Rain Forest", River "River (Canoe/White‐Water Rafting)", Mountain "Mountain Climbing" }; 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
Survey Programming Fundamentals Chapter 6 Shared Lists
71
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.
Chapter 6 Shared Lists Survey Programming Fundamentals
72
Survey Pr
ChapteYou may to prevensorting o
The type
Item Rotate
RandomiReverse
AscendinDescend
You can uin the ne
rogramming
er 7 Soneed to channt bias withinptions for mr
s of sorts ava
ize
ng ing
use any of thext sections.
There when hold ththe pa
This
Fundamental
rting Catenge the ordern a survey or srInterview.
ailable in mrIn
DescriptioThe categolist. The categoThe categois presenteThe categoThe catego
e sorting feat
is a differencusing the samhe same pattattern for eac
chapter w
Change th
Use the sometadata
Ensure cerwithin a so
ls
egorical Rr of the categsimply to re‐o
nterview are a
on ory list is rota
ory list is presory list is reveed top‐down ory list is sortory list is sort
tures above in
ce using the rame response ltern for each qh question.
will show
e order of you
orting commanand routing se
rtain responsesorted list
C
Responseorical responorder the list
as follows:
ated by one c
sented in ranersed before to the first reted in ascendted in descen
n either the m
andomize fealist for multipquestion per
w you how
r response list
nds in both theections
s are not sorte
Chapter 7 Sor
Lists ses in a questalphabeticall
ategory befo
domized ordeeach presentespondent, bing alphabetiding alphabe
metadata or t
ature in the mle questions.respondent; t
w to:
s
ed
rting Categori
tion. This is sy. This chapt
re each prese
er. tation. This mottom‐up to tcal order. tical order.
he routing se
metadata and Using the mthe routing m
ical Response
sometimes doter will cover
entation of th
means that thethe next, etc.
ections as sho
routing sectietadata meth
method will ch
e Lists
73
one the
he
e list .
own
ons hod will hange
Chapter 7 Sorting Categorical Response Lists Survey Programming Fundamentals
74
Example
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.
Name "Text" categorical [min..max] {ID1 "AltText1", IDn "AltTextn" } sortingkeyword;
Item Description Name Unique identifier for the item within your questionnaire. They must start with a
letter or underscore ( _ ) and contain only alpha‐numeric 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, AltTextn
Optional text to show the respondent instead of the name of the question. This 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.
Metadata (en‐US, Question, Label)
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
Survey Programming Fundamentals Chapter 7 Sorting Categorical Response Lists
75
Example
Routing Section Sorting In the routing section, the syntax for sorting is:
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)
Souvenirs.Categories.Order=orderconstants.oAscending
Souvenirs.Ask()
End Routing
The above statement will sort the list alphabetically A to Z.
Not Sorting Specific Responses There may be certain responses that you do not want sorted within a list, such as “None of These” or “All of These”. To force a group of categories to retain its original position when the overall category list is sorted, use the keyword fix.
Name "Text" categorical [min..max]
{ID1 "AltText1" fix,
IDn "AltTextn"} sortingkeyword;
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)
Chapter 7 Sorting Categorical Response Lists Survey Programming Fundamentals
76
Example
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.
Metadata (en‐US, Question, Label) TravelHelp "Have you used any of the following to help you with your travel arrangements?" Categorical [1..] { TravelBooks "Travel Books" { LonelyPlanetBook "Lonely Planet", Fodor "Fodor's" , Frommer "Frommer's" , otherBooks "Other Travel Book" other fix } ran, Websites { Expedia , Orbitz, Govt "Government Websites", otherwebsite "Other Website" other fix } ran, Noneofthese "None of these" style (indent = 0) fix exclusive } ran; End Metadata
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.
Survey Programming Fundamentals Chapter 7 Sorting Categorical Response Lists
77
Example
Keeping Specific Categories Grouped Together You may need to keep pairs or groups of categories together within a list, even when adding randomization. You can achieve this by creating a sublist with the items that need to be kept together, while randomizing the main question. The example below will randomize the TypeAccom question but always keep the responses in the define list resorts together.
Metadata (en‐US, Question, Label) Resorts define { FamilyResorts "Family Resorts", CouplesResorts "Couples Resorts" }; TypeAccom "At what type of accommodations did you stay?" categorical [1..1] { Hotel , Motel , BedBreakfast "Bed and Breakfast", Hostels , use Resorts sublist , OtherAccom "Other Accommodations" other fix } ran; End Metadata
Chapter 7 Sorting Categorical Response Lists Survey Programming Fundamentals
78
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 Winn‐Dixie 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 Non‐Prepared Foods Meat/Seafood Produce Canned Goods Pasta/Grains None of These
Survey Pr
ChapteThe logicwe can le
Filter CThe Filter
R E
Item Name CategorieFilter condition
rogramming
er 8 Rec behind the searn how to p
Categoriesr property ca
Routing(Web Name.Cate Name.Ask()End Routing
DesUni
es ProPro
n Rep
Fundamental
estricting survey is an impresent the re
s n be used to
) gories.Filter=)
scription ique identifieoperty (keywooperty (keywopresents anyt
In this c
Filter respbased on p
Filter resp
Limit the mfor numer
ls
Responsemportant partespondent wi
limit the cate
=condition
r for the quesord) of the quord) to state ything that stat
hapter w
onses displayeprevious answe
onses based o
maximum or mic questions ba
es t of research ith logical cho
egories displa
stion name. uestion denotyou are restrites the categ
we will:
ed on a questioers to question
n your interna
minimum amouased on logic
Ch
to ensure accoices.
ayed by a que
ting the respocting the cateories to displ
on ns
l logic
unts
hapter 8 Rest
curate data.
stion in the r
onses egories for thay for the qu
tricting Respo
In this sectio
outing sectio
he question estion
onses
79
n,
n.
Chapter 8 Restricting Responses Survey Programming Fundamentals
80
Example
Here is an example in which we are asking respondents to choose all the hotel chains they have stayed in the past year. The follow‐up question is “Of those chains, which is your favorite?” The response list for the follow‐up question is restricted to only the answers given in the first question.
Metadata (en‐US, Question, Label) HotelChainStayed "Choose the hotel chains you have stayed at this past year." categorical [1..] { InterContinental, Cendant, Marriott, Accor, Choice, Hilton, DontKnow "Don’t Remember" DK, Refused "Prefer not to Answer" REF }; FavHotelChain "Of those chains, which one would you most prefer to stay at again?" categorical [1..1] { InterContinental, Cendant, Marriott, Accor, Choice, Hilton, DontKnow "Don’t Remember" DK, Refused "Prefer not to Answer" REF }; End Metadata Routing(Web) HotelChainStayed.Ask() FavHotelChain.Categories.Filter=HotelChainStayed.Response.Value FavHotelChain.Ask() End Routing
Survey Programming Fundamentals Chapter 8 Restricting Responses
81
If you choose:
The result will be:
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.
Chapter 8 Restricting Responses Survey Programming Fundamentals
82
Example
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." categorical [1..] { InterContinental, Cendant, Marriott, Accor, Choice, Hilton, DontKnow "Don’t 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 "Don’t Remember" DK, Refused "Prefer not to Answer" REF }; Routing(Web) HotelChainStayed.Ask() FavHotelChain.Categories.Filter=HotelChainStayed.Response.Value FavHotelChain.Ask() End Routing
Survey Programming Fundamentals Chapter 8 Restricting Responses
83
If you choose:
The result is:
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.
Chapter 8 Restricting Responses Survey Programming Fundamentals
84
Example
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 year." categorical [1..1] { InterContinental, Cendant, Marriott, Accor, Choice, Hilton, DontKnow "Don’t 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 "Don’t 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 "Don’t Remember" DK, Refused "Prefer not to Answer" REF };
Survey Programming Fundamentals Chapter 8 Restricting Responses
85
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
Chapter 8 Restricting Responses Survey Programming Fundamentals
86
Example
Limiting Numeric Question Ranges Based on Logic Another aspect of accurate data is to be able to set the minimum or maximum amount that can be entered for a numeric response based off previous answers from the respondent. You can control the minimum and maximum values for a question with the following statements in the routing section.
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
Metadata(en‐US, Question, label) AmtSpentonHoliday "Approximately how much in total did you spend last year on your holidays/vacations?" long [0..10000]; 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
Survey Programming Fundamentals Chapter 8 Restricting Responses
87
If you answered 5000 for the question AmtSpentonHoliday, then tried to submit an answer greater than 5000 for AmtSpentAir, you would see the following:
Chapter 8 Restricting Responses Survey Programming Fundamentals
88
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 SouthwesternInternational Cuisine Italian Russian Polish French Caribbean None of These
FavCuisine Of those mentioned, which one do you prefer?
American Cuisine Barbecue Cajun Southern SouthwesternInternational Cuisine Italian Russian Polish French Caribbean None of These
OrderMealOut On average, how many meals per week do you order from a restaurant?
(If zero to OrderMealOut, skip to Thanks)
Survey Programming Fundamentals Chapter 8 Restricting Responses
89
EatMealOut Of those meals, how many do you eat at the restaurant, as opposed to home delivery or carry‐out?
(If zero to EatMealOut, skip to Thanks)
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) ________________________
Thanks Thank you for your input.
Chapter 8 Restricting Responses Survey Programming Fundamentals
90
Survey Pr
ChapteBy defaudisplay m
You can p
• Ps
• Bmaw
rogramming
er 9 Mult mrInterviewmultiple quest
place multiple
Page metadatscreen. If you
Block metadamultiple quesand organizatwith the analy
Fundamental
ultiple Quw displays ontions on the s
e questions o
ta items referu are only tryi
ta items conttions. The btional purposeysis products
In this c
Learn to psame scree
Discuss theblocks
Learn to cothe screen
ls
uestions one question pesame screen.
on the same s
rence other qing to present
tain other quelock type canes. For exampmrTables and
hapter w
lace multiple qen
e differences b
ontrol if a quesn or in what ord
on One Paer screen. Th
screen by usin
uestions in tht more than o
estions, similn be used to gple, if you ared Desktop Re
we will:
questions on th
between pages
stion is presender.
Chapter 9 M
age here will be ti
ng page or blo
he metadata one question
ar to how a ggroup a list ofe trying to groeporter.
he
s and
ted on
Multiple Quest
mes when yo
ock statemen
to group themon a screen,
grid question f questions fooup questions
tions on One
ou will want t
nts.
m on the samuse a page.
can contain or presentatios together for
Page
91
o
me
on r use
Chapter 9 Multiple Questions on One Page Survey Programming Fundamentals
92
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.
In the metadata section:
Name "text" page(QuestionName1, QuestionName2, QuestionNameN);
Item Description Name Unique identifier for the item within your questionnaire. They must start with a
letter or underscore ( _ ) and contain only alpha‐numeric 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, QuestionName2, QuestionNamen
Represents the question names to display on the page together.
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. Right‐click to choose Copy as Ask.
Survey Programming Fundamentals Chapter 9 Multiple Questions on One Page
93
Example
The following is an example showing multiple demographic questions on the same screen.
Metadata (en‐US, Question, label) HouseHold "Including yourself, how many people currently live in your household?" long [1 .. 99]; Age "To which of the following age categories do you belong?" Categorical [1..1] { Under18 "Under 18", _18to34 "18 to 34", _35to54 "35 to 54", _55plus "55 and over" , Refused "Prefer not to Answer" REF }; Participate "Check here if you wish to participate in future studies on travel." boolean; Demos "Now a few demographic questions" page( HouseHold, Age, Participate ); End Metadata Routing Demos.Ask() End Routing
Chapter 9 Multiple Questions on One Page Survey Programming Fundamentals
94
Will display as:
Block Blocks are metadata items that contain the questions you want displayed together on a screen.
Name "text" block fields
(
QuestionName1 "text" QuestionType;
QuestionNamen "text" QuestionType;
);
Survey Programming Fundamentals Chapter 9 Multiple Questions on One Page
95
Example
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, QuestionNamen
Represents the questions contained inside the block
In the routing, ask the block name:
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.
Metadata (en‐US, Question, label) Demos "Now a few demographic questions" block fields ( HouseHold "Including yourself, how many people currently live in your household?" long [1 .. 99]; Age "To which of the following age categories do you belong?" categorical [1..1] { Under18 "Under 18", _18to34 "18 to 34", _35to54 "35 to 54", _55plus "55 and over" , Refused "Prefer not to Answer" REF }; Participate "Check here if you wish to participate in future studies on travel." boolean; ); End Metadata Routing Demos.Ask() End Routing
Chapter 9 Multiple Questions on One Page Survey Programming Fundamentals
96
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
Survey Programming Fundamentals Chapter 9 Multiple Questions on One Page
97
Example
The following example shows how you would refer to questions in a block within the routing section.
Metadata (en‐US, Question, label) AgeGroups "" define { Under18 "Under 18", _18to34 "18 to 34", _35to54 "35 to 54", _55plus "55 and over" }; Demos "Now a few demographic questions" block fields ( HouseHold "Including yourself, how many people currently live in your household?" long [1 .. 99]; Age "To which of the following age categories do you belong?" categorical [1..1] { use AgeGroups , Refused "Prefer not to Answer" REF }; Participate "Check here if you wish to participate in future studies on travel." boolean; ); 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() If Demos.household.Response.Value > 1 then KidsAtHome.Ask() End if End Routing
Chapter 9 Multiple Questions on One Page Survey Programming Fundamentals
98
Example
Controlling How Page and Block Questions are Displayed You can control the page or block questions asked on the screen by:
• Filtering the page or block
• Using a sorting keyword on the page/block
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.
Name.QuestionFilter= “Question1, QuestionN”
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, questionN
Represents questions that will be added to the questionfilter and shown on the screen.
The following will not show the question asking to participate in future studies if they are already a member of our panel group.
Metadata (en‐US, Question, label) Membership "Are you currently a member of our panel?" Categorical [1..1] { Yes, No }; HouseHold "Including yourself, how many people currently live in your household?" long [1 .. 99]; Age "To which of the following age categories do you belong?" categorical [1..1] { Under18 "Under 18", _18to34 "18 to 34", _35to54 "35 to 54", _55plus "55 and over" Refused "Prefer not to Answer" REF };
Survey Programming Fundamentals Chapter 9 Multiple Questions on One Page
99
Example
Participate "Check here if you wish to participate in future studies on travel." boolean; Demos "Now a few demographic questions" page( HouseHold, Age, Participate ); End Metadata Routing(Web) Membership.Ask() If Membership={Yes} then Demos.QuestionFilter=”Household, Age” Demos.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) ' Using Demos from the previous examples Demos.QuestionOrder=OrderConstants.oRandomize Demos.Ask()
End Routing
Chapter 9 Multiple Questions on One Page Survey Programming Fundamentals
100
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
Survey Pr
ChapteMany surtimes. Th
If your qu
Please ra
Aruba BermudaFlorida Hawaii Fiji Costa RicThailand
This is a gthat mak
• A
• Da
You will asee themseparate interest i
rogramming
er 10 Rerveys involve he concept is
uestionnaire
ate the followExtremInterest
a
ca
good exampleke it a loop/gr
All share the s
During analysalso want to s
also need to dm above (i.e., oscreen (i.e., "n visiting., et
Fundamental
epetitive Qthe concept sometimes c
contains a se
wing travel deely ted
SomeInter
e of when to rid are:
same respons
is, we will wasee the result
decide if you on the screen"Please rate Ac., ")
In this c
Understansurvey
Create me
Review dif
ls
Questionsof asking thecalled a grid o
ries of questi
estinations oewhat rested N
use the loop/
ses (Extremel
ant to see thets in summary
want to haven all at once),Aruba on you
hapter w
nd when to use
etadata for grid
fferent types o
Chap
s Loops & same basic qor a loop.
ions that look
n your intere
Neutral D
/grid metadat
y Interested,
e results of eay in the forma
e the appeara or would weur interest in v
we will:
e a grid or a loo
ds and loops
of grids/loops
ter 10 Repet
& Grids question with
k similar to th
est in visiting Somewhat
Disinterested
ta item. The
Somewhat In
ach destinatioat they appea
ance of the que prefer that evisiting., Plea
op in a
titive Questio
h different att
his:
the locationExtremely
Disinterested
properties th
nterested, etc
on separately,ar in above.
uestions to beeach questionse rate Berm
ons ‐ Loops &
tributes multi
.
d
his question h
c.)
, but perhaps
e exactly as wn be on a uda on your
Grids
101
iple
has
s will
we
Chapter 10 Repetitive Questions ‐ Loops & Grids Survey Programming Fundamentals
102
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.
Name "GridText" loop
{
ID1 "Alt Text1",
IDn "Alt Textn"
} fields
(
Question1 "LoopText1 {@} ";
Questionn "LoopTextn {@}"
) 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", IDn"Alt Textn"
Defines the category list that controls the number of repetitions required. You 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, Questionn
Questions that will be repeated based on the category list (ID1, ID2).
LoopText1, LoopTextn
Defines an optional label that will be displayed when the questions in the loop 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 semi‐colon.
Survey Programming Fundamentals Chapter 10 Repetitive Questions ‐ Loops & Grids
103
Example
Here is the syntax for the grid shown at the beginning of this chapter.
Metadata (en‐US, Question, label) InterestinLocation "Please rate the following travel destinations on your interest in visiting the location." loop { Aruba , Bermuda, Florida, Hawaii, Fiji, CostaRica, Thailand } fields ( Rating "" categorical [1..1] { ExtremelyInterested "Extremely Interested", SomewhatInterested "Somewhat Interested", Neutral "Neutral ", SomewhatDisinterested "Somewhat Disinterested", ExtremelyDisinterested "Extremely Disinterested" }; ) expand grid;
End Metadata
Routing(Web) InterestinLocation.Ask()
End Routing
Chapter 10 Repetitive Questions ‐ Loops & Grids Survey Programming Fundamentals
104
In the previous example, since we asked the question using the loopname.Ask(), the survey will appear in this format:
This is what this manual will refer to as a grid 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.
Survey Programming Fundamentals Chapter 10 Repetitive Questions ‐ Loops & Grids
105
Example
If we add text to the Rating question metadata and change the statement in the routing:
Metadata (en‐US, Question, label) InterestinLocation "Please rate the following travel destinations on your interest in visiting the location." loop { Aruba , Bermuda , Florida, Hawaii, Fiji, CostaRica, Thailand } fields ( Rating "Please rate {@} on your interest in visiting." categorical [1..1] { ExtremelyInterested "Extremely Interested", SomewhatInterested "Somewhat Interested", Neutral "Neutral ", SomewhatDisinterested "Somewhat Disinterested", ExtremelyDisinterested "Extremely Disinterested" }; ) expand grid;
End Metadata Routing(Web) InterestinLocation[..].Ask() End Routing
Chapter 10 Repetitive Questions ‐ Loops & Grids Survey Programming Fundamentals
106
Then the survey will come up one question at a time on the screen. The first time you will see:
A few things to remember about the previous example:
• 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()
For Each loops An alternative way to write [..] and still have the questions come up individually on the screen would be using a For Each loop statement.
Dim var
For each var in LoopName
var.Ask()
Next
Survey Programming Fundamentals Chapter 10 Repetitive Questions ‐ Loops & Grids
107
Example
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 Next
Marks the start and end of a loop. In this case, the loop is doing what’s inside 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.
Metadata (en‐US, Question, label) InterestinLocation "Please rate the following travel destinations on your interest in visiting the location." loop { Aruba , Bermuda , Florida, Hawaii, Fiji, CostaRica, Thailand } fields ( Rating "Please rate {@} on your interest in visiting." categorical [1..1] { ExtremelyInterested "Extremely Interested", SomewhatInterested "Somewhat Interested", Neutral "Neutral" , SomewhatDisinterested "Somewhat Disinterested", ExtremelyDisinterested "Extremely Disinterested" }; ) expand grid;
End Metadata
Chapter 10 Repetitive Questions ‐ Loops & Grids Survey Programming Fundamentals
108
Example
Routing(Web) Dim location For each location in InterestinLocation location.Ask() Next 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.
Categorical Loops with a Numeric Question Another example will show changing the type of question in the loop. This metadata example displays numeric questions instead of a categorical scale.
ExpenseCategories define
{ Transportation,
Accomodations,
FoodDrink "Food and Drinks",
OtherMisc "Other Miscellaneous"
};
BusTravelSpent "In the past year, approximately how much did you spend in each category listed below for business travel?" loop
{ use ExpenseCategories} fields
(
BusTravel "Amount Spent on Business Travel"
long [0 .. ];
) expand grid;
Survey Programming Fundamentals Chapter 10 Repetitive Questions ‐ Loops & Grids
109
Example
Would display in the browser like this:
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:
Metadata (en‐US, Question, label) ExpenseCategories define { Transportation, Accomodations, FoodDrink "Food and Drinks", OtherMisc "Other Miscellaneous" }; 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 .. ]; LeisureTravel "Leisure Travel" long [0 .. ]; ) expand grid; Routing
TravelSpent.Ask()
End Routing
Chapter 10 Repetitive Questions ‐ Loops & Grids Survey Programming Fundamentals
110
Survey Programming Fundamentals Chapter 10 Repetitive Questions ‐ Loops & Grids
111
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.
Name "GridText" loop [n1..n2]
fields
(
Question1 "LoopText1 {@}";
Question2 "LoopText2 {@}"
) 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, Questionn
Questions that will be repeated based on the category list (ID1, ID2).
LoopText1, LoopTextn
Defines an optional label that will be displayed when the questions in the loop 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.
Description Example Results Ranges [1..10] Will display the question in the grid/loop 10 times Single Values [1,5,10] Will display the questions in the grid/loop 3 times, each time
representing one of the numbers listed Step Values [1..10 step 2] Will display the questions in the grid/loop 5 times, each time
representing an odd number 1 to 9. Exclusive Values [1..10 ^5] Will display the questions 9 times, eliminating the 5th time.
Chapter 10 Repetitive Questions ‐ Loops & Grids Survey Programming Fundamentals
112
Example
The following will produce a pair of questions asked about the respondent’s last three trips.
Metadata (en‐US, Question, label) Last3Trips "Please think about the last three times you traveled for business or pleasure and answer the following questions." loop [1..3] fields ( BusorLeis "Tell us about Trip # {@}. Was this trip for..." categorical [1..1] { Business , Leisure, Both }; 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
Survey Programming Fundamentals Chapter 10 Repetitive Questions ‐ Loops & Grids
113
The first time through the loop you will see:
Chapter 10 Repetitive Questions ‐ Loops & Grids Survey Programming Fundamentals
114
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.
(ASK MEALTIME & MEALORIGIN ABOUT EACH MEAL.)
MealTime Thinking about the last [INSERT MEAL] you had, what time did you eat [INSERT MEAL]?
MealOrigin Was your [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
StronglyAgree
Agree Neutral Disagree Strongly Disagree
Breakfast is the most important meal of the day Eating fast food can be healthy I have a well‐balanced diet I don’t eat a lot of sugar
HealthComm Please add any additional comments you have about the importance of healthy foods in restaurants.
Survey Pr
ChapteNow thatsolving sk
Some of
• H
• St
• Vt
Auto AIf you wothen youresponse
From the
rogramming
er 11 Det we are startkills. mrStudi
the items wit
Have mrStudi
Set points witto investigate
View the elemtest your scrip
Answer Quould like to vie can have mres each quest
e menu, choo
Fundamental
ebugging ting to learn mio provides m
thin mrStudio
o produce te
thin your scrip current valu
ments of a quept.
estionnairew your skip rStudio automion received.
se the AutoA
In this c
Review coyour script
Create tes
Create you
ls
Tools witmore complexmany tools to
o which may h
st data for re
pt that the sues.
estion, such a
re patterns andmatically answ
Answer icon sh
hapter w
ncepts to helpt
t data within m
ur own macros
Ch
thin mrStx question tyhelp you in c
help you in te
view.
urvey will stop
as its style or
view what’s wer the quest
hown below:
we will:
p you troublesh
mrStudio
s
hapter 11 De
tudio pes, we needreating more
esting your sc
p the action a
controls, to s
happening intions for you a
hoot
ebugging Too
d to have som complex sur
cripts are the
as you are tes
see the curre
n your routingand display th
ls within mrS
me problem veys.
ability to:
sting to allow
nt values as y
g at a high levhe number of
tudio
115
you
you
vel, f
Chapter 11 Debugging Tools within mrStudio Survey Programming Fundamentals
116
You will be prompted for the number of interviews you wish to produce and the number of attempts the system should make per question.
The result will show in the AutoAnswer window as shown below:
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.
Survey Programming Fundamentals Chapter 11 Debugging Tools within mrStudio
117
Producing Test Data Besides seeing the summary of answers created, we can also store those results to use as data checks before the study goes live. With mrStudio, you can write to SPSS .SAV, .XML, Dimensions Data file (.DDF), and Dimensions RDB database formats.
• From the menu choose Tools • Select Write to Database
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.
Chapter 11 Debugging Tools within mrStudio Survey Programming Fundamentals
118
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.
Survey Programming Fundamentals Chapter 11 Debugging Tools within mrStudio
119
Adding Additional Data Sources After setting your data source the first time, mrStudio will automatically write to this file each time. mrStudio allows you to add multiple data sources if you wish to make test data in multiple formats. View the Metadata Explorer and find the datasources collection. Right‐click on the folder and choose Add DataSources. You will see the menu to choose the datatype and filename.
Now you will be able to Right‐click on DataSources and choose Change DataSource to choose which datasource you want to create test data for.
Chapter 11 Debugging Tools within mrStudio Survey Programming Fundamentals
120
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 re‐testing at that point.
• Set a breakpoint in your routing at the question you want to review • Choose AutoAnswer • When prompted, make sure to choose Number of interviews to be set to 1 • This will stop auto‐answering at the question in which you set the breakpoint • Now choose F5 to continue out of AutoAnswer mode
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.
Survey Programming Fundamentals Chapter 11 Debugging Tools within mrStudio
121
Troubleshooting Specific Sections of Code Another helpful feature is to step through the lines of the routing section, so you can pause and evaluate each action. Then you can see the current values of questions or variables with the Expressions tab or the locals pane.
To step through code, choose the F10 key or Debug ‐ Single Step.
Next, investigate specific question values or properties.
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.
Chapter 11 Debugging Tools within mrStudio Survey Programming Fundamentals
122
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.
Survey Programming Fundamentals Chapter 11 Debugging Tools within mrStudio
123
Working with Macros mrStudio contains macros to help you create scripts. You have the ability to add new macros and modify or delete existing macros.
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:
• mrScriptBasic: The macros will appear in the routing section
• mrMetadataScript: The macros will appear in the metadata section
Updating/Deleting Existing Macros Choose an existing macro from the list shown in the previous screenshot. Make any changes desired in the Macro Text or Macro Name areas and choose the Update Macro icon. To delete an existing macro, choose the macro and select the Delete Macro icon.
Adding Additional Macros Create the code you wish to make into a macro. Then copy the code and choose Tools – Macros. Choose the appropriate area to place your macro (mrScriptBasic or mrMetadataScript), then copy the code into the Macro Text window (Ctrl – V). Create a unique name for the macro in the Macro Name area. Then select the Add Macro icon.
Chapter 11 Debugging Tools within mrStudio Survey Programming Fundamentals
124
You can copy macros from one machine to another by copying the file,
C:\Documents and Settings\<your Windows user name>\Application Data\SPSS\ mrStudio\4.5.0.0\MacroDefinitions.xml.
Survey Pr
ChapteWe have Adding fi
PrevioSuppose
If the resreferencetravel guto write t
rogramming
er 12 Colearned to crlter logic to lo
us Responyou have the
ponse is “Neve the travel gides, then wethis logic with
T
Fundamental
nditionedreate filteredoops and grid
nses Withie following qu
ver”, the respuide, Lonely e must place thin the routin
his chapter
Prev
Prevouts
Prevques
A su
ls
d Loops a questions bads is the same
in the Loopuestion:
pondent shouPlanet?” If wthe questionsng section.
r looks at lo
vious response
vious responseside the loop/g
vious responsestions
ublist of catego
and Grids ased on answe concept.
p
uld not see thwe wish to reps within a loo
ops/grids f
es within the lo
es to a simple qgrid
es to a differen
ories
Chapter 12
wers to previo
e follow up qpeat these pap. The follow
iltered on:
oop
question
t loop/grid’s
2 Conditione
us questions
question, “Whirs of questiowing loop dem
ed Loops and
and logic.
hy do you ons for multipmonstrates ho
Grids
125
ple ow
Chapter 12 Conditioned Loops and Grids Survey Programming Fundamentals
126
Example
Metadata (en‐US, Question, label) TravelGuides "Now, some questions about Travel Guides." loop { LonelyPlanetBook "Lonely Planet" , Fodor "Fodor's", Frommer "Frommer's" } fields ( Read "How often do you read or reference the travel guide, {@}?" categorical [1..1] { Weekly , Monthly , Yearly, Rarely , Never }; WhyRead "Why do you reference the travel guide, {@}?" categorical [1..] { Hotel "Advice on Hotels", Neighborhoods "Information on Neighborhoods" , Attractions "Tourist Attractions" , SaveMoney "Tips on how to save money" , Transportation "Local travel/transportation" , OtherReason "Other Reason" other , Refused "Prefer not to Answer" REF }; ) 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
Survey Programming Fundamentals Chapter 12 Conditioned Loops and Grids
127
Example
Breaking down the example above:
• 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 tguide’s response to the read question was not “Never”, then ask the follow‐up question, WhyRead
Loops/Grids Filtered on Previous Responses Outside the Loop/Grid In previous examples, we could filter the response list of a question by the responses to previous questions. We can apply that same principle to the category list of a grid/loop. Instead of filtering the categories of a question, we will do a QuestionFilter on a loop:
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.
Metadata(en‐US, Question, Label) ResortTypes "" define { Historical, AmusementPark "Amusement Park" , Beach "Beach" , Adventure "Adventure" }; AttendedResort "From the list below, please indicate which types of resorts you have stayed at." categorical [1..] {use ResortTypes};
Chapter 12 Conditioned Loops and Grids Survey Programming Fundamentals
128
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:
Survey Programming Fundamentals Chapter 12 Conditioned Loops and Grids
129
You will only have the responses chosen as the categories of the grid:
Loops/Grids Filtered on Responses to a Different Loop/Grid’s Questions Sometimes the filter conditions can become more complex. Let’s think about another scenario. Looking at the grid from the last example:
…suppose the follow‐up question was,
“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.
Chapter 12 Conditioned Loops and Grids Survey Programming Fundamentals
130
Example
To correctly ask this follow‐up, we need to:
• 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.
Metadata (en‐US, Question, Label) ResortTypes "" define { Historical, AmusementPark "Amusement Park" , Beach "Beach" , Adventure "Adventure" }; 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; WhyLoop "" loop { use ResortTypes } fields ( WhyVerySat "Why are you satisfied overall with the {@} resort?" text; ) expand grid; End Metadata
Survey Programming Fundamentals Chapter 12 Conditioned Loops and Grids
131
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.
Loops/Grids Filtered on a Sublist of Categories As we have learned in previous chapters, we can create sublists to make define lists more reusable. You can also use sublists to create “groups” to be used as category filters.
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 follow‐up grid question will display a define list with business travel attributes (BusinessAttribs), leisure travel attributes (LeisureAttribs) or both lists.
Chapter 12 Conditioned Loops and Grids Survey Programming Fundamentals
132
Example
Metadata (en‐US, Question, Label) BusinessAttribs define { MeetInPerson "I think meeting face‐to‐face improves work communication." , WeekendTravel "Traveling on the weekends interferes with my personal time." , ArriveEarly "I like to arrive early to prepare for the next day's agenda." }; LeisureAttribs define { ShortDistance"I like to take many short weekend trips vs one long vacation/holiday.", family "Travel is a great time to reconnect with my family members.", cost "I often splurge on vacation/holidays, picking the nicest hotels and locations." }; primarytravel "Do you primarily travel for..." categorical [1..1] { Business , Leisure , Both };
TravelAttribs "Rate your agreement with the following statements." loop { use BusinessAttribs sublist ran, use LeisureAttribs sublist ran } ran fields ( attrib "" categorical [1..1] { SAgree "Strongly Agree" , Agree, Neutral , Disagree , SDisagree "Strongly Disagree" }; ) expand grid; End Metadata
The routing section would look like this:
Survey Programming Fundamentals Chapter 12 Conditioned Loops and Grids
133
Example
Routing(Web) 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
The code above will display:
• 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
Breaking down the code above:
• 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 question’s 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.
Chapter 12 Conditioned Loops and Grids Survey Programming Fundamentals
134
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:
Deli/Carry Out Restaurants without Seating
Fast Food Restaurants
Family/Casual Dining Restaurants
Upscale Restaurants)
Eaten Have you ever eaten in [INSERT TYPE OF RESTAURANT]?
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.
Very
Satisfied SomewhatSatisfied
Neutral Somewhat Dissatisfied
Very Dissatisfied
Deli/Carry Out Restaurants without Seating
Fast Food Restaurant
Family/Casual Dining Restaurant
Upscale Restaurant
Survey Programming Fundamentals Chapter 12 Conditioned Loops and Grids
135
(If Yes to Fast Food in Eaten Question, ask ChainAware and FastFoodQual.)
ChainAware Which of the following fast food chains have you eaten at?
Wendy’s McDonald’s Burger King Arby’s In‐N‐Out Burger None of these
(Of the fast food chains mentioned in ChainAware)
FastFoodQual Please rate your overall satisfaction with the quality of food obtained in the following fast food restaurants.
Very
Satisfied SomewhatSatisfied
Neutral Somewhat Dissatisfied
Very Dissatisfied
Wendy’s McDonald’s Burger King Arby’s
In‐N‐Out Burger
Chapter 12 Conditioned Loops and Grids Survey Programming Fundamentals
136
Survey Pr
ChapteLook andterms of
OverviTo fully uoverall fomrInterv
1) Hp
2) Sr
For examtemplate
Now thattake a clo
TemplaTemplatea survey.questiontemplate
rogramming
er 13 Cod feel can be amodifying th
iew of the utilize the capormatting of tiew survey ar
HTML Templapages that areStyles within trouting sectio
mple, if you foe, then the qu
t you have a boser look at e
ates es are HTML p Templates cnaire as you ces for re‐use i
In t
Fundamental
ntrollinga crucial eleme look of you
Formattinpabilities of anthe survey wore:
ates (includine applied to ythe script. Thon.
ormat a specifuestion style w
basic understeach aspect.
pages which hcontrol the lacreated it in tn many proje
this chap
Different wappearanc
How to ap
How to effscript
ls
the Lookment of surveyur survey.
ng of a Surn mrIntervieworks. The hie
g Cascading Syour survey.hese are scrip
fic question wwill override t
tanding of how
have special myout of the mthe metadataects. You can
pter we
ways to changece of your surv
pply different lo
fectively use st
Cha
k of Your Sy scripting. m
rvey w survey’s aperarchy of item
Style sheets a
pting properti
with a style inthe template’
w templates
mrInterview “mrInterview pa. This allowsalso use mor
will lear
e the overall ey
ooks to your su
tyles within yo
pter 13 Cont
Survey mrInterview p
pearance, yoms that affect
and .xml files)
ies added to e
a way that co’s format for
and styles are
“tags” that repage separates you the flexire than one te
rn:
urvey
ur
trolling the Lo
provides great
u need to undt the appeara
). These are s
either the me
ontradicts whthat question
e applied to t
epresent the de from the texibility to createmplate with
ook of Your Su
t flexibility in
derstand howance of an
special HTML
etadata or the
hat is in the Hn.
the survey, le
different partxt of your te standard hin a survey.
urvey
137
w the
e
HTML
t’s
ts of
Chapter 13 Controlling the Look of Your Survey Survey Programming Fundamentals
138
The three main types of templates are:
• 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 sub‐templates for the aspects that change.
• Sub‐Template: A template file that defines the layout of one aspect of the page. For example, you can create sub‐templates 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 sub‐templates 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 language’s 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:
1. Project folder – specific language passed as the current interview’s language 2. Project folder – default language 3. Project folder 4. Global templates folder – specific language passed as the current interview’s language 5. Global templates folder – default language 6. Global templates folder
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
Survey Programming Fundamentals Chapter 13 Controlling the Look of Your Survey
139
Applying a Template within Your Script. To apply a template within the routing section:
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 sub‐template (such as java‐script logic to check a specific question, or a complex question style), you may choose to add the template to the metadata:
Metadata(en‐US, Question, Label)
Name "text"
templates(Question = "templatename.htm" ) questiontype
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 question’s type (categorical, long, text, etc.) Note that the
template goes before the question type keyword.
Chapter 13 Controlling the Look of Your Survey Survey Programming Fundamentals
140
Example
Below is an example of applying a template to the entire survey.
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 Built‐in 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.
Survey Programming Fundamentals Chapter 13 Controlling the Look of Your Survey
141
Tips for Scriptwriters Regarding Templates A few things to think about as you are using mrStudio to apply your templates:
• 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 sub‐types. 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:
Chapter 13 Controlling the Look of Your Survey Survey Programming Fundamentals
142
Example
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. Let’s 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
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.
Survey Programming Fundamentals Chapter 13 Controlling the Look of Your Survey
143
Example
Categories The category default styles section is used to apply formatting to categorical responses.
IOM.DefaultStyles.Categories[CategoryStyleTypes.CategoryStyleTypeEnum]
Where the CategoryStyleTypesEnums are as follows:
CategoryStyleTypeEnum Description csSingle Single response categorical. csMulti Multi‐response categorical. csExclusive Exclusive response categorical. csList Subheading Text.
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.
Chapter 13 Controlling the Look of Your Survey Survey Programming Fundamentals
144
Example
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]
Where the GridStyleTypesEnums are as follows:
GridStyleTypes Enum Description gsCell The cells of a grid. gsAltRow The alternating rows of a grid. gsAltCol The alternating columns of a grid. gsRowHeader The row headings of a grid. gsColHeader The column headings of a grid. gsAltRowHeader The alternate row headings of a grid. gsAltColHeader The alternate column headings of a grid.
Routing(Web) 'Default Grid Formatting With IOM.DefaultStyles 'Row cell items .Grids[GridStyleTypes.gsCell].Cell.BorderColor = "black" .Grids[GridStyleTypes.gsCell].Cell.BorderStyle = BorderStyles.bsSolid .Grids[GridStyleTypes.gsCell].Cell.BorderWidth = 1 'Alternate cell items .Grids[GridStyleTypes.gsAltRow].Cell.BgColor = "#D5D5D5;" 'Row Headings .Grids[GridStyleTypes.gsRowHeader].Cell.BorderColor = "black" .Grids[GridStyleTypes.gsRowHeader].Cell.BorderStyle=BorderStyles .bsSolid .Grids[GridStyleTypes.gsRowHeader].Cell.BorderWidth = 1 .Grids[GridStyleTypes.gsRowHeader].Cell.width= "120px" 'Column Headings .Grids[GridStyleTypes.gsColHeader].Cell.BgColor = "#800000;" .Grids[GridStyleTypes.gsColHeader].Color = "#FFFFFF;" .Grids[GridStyleTypes.gsColHeader].Font.Effects = FontEffects.feBold .Grids[GridStyleTypes.gsColHeader].Cell.BorderColor = "black" .Grids[GridStyleTypes.gsColHeader].Cell.BorderStyle = BorderStyles.bsSolid .Grids[GridStyleTypes.gsColHeader].Cell.BorderWidth = 1 .Grids[GridStyleTypes.gsColHeader].VerticalAlign = VerticalAlignments.vaBottom .Grids[GridStyleTypes.gsColHeader].cell.wrap=true .Grids[GridStyleTypes.gsColHeader].cell.width= "90px" 'Alternate Row Headings .Grids[GridStyleTypes.gsAltRowHeader].Cell.BgColor = "#CECECE;" End With
Survey Programming Fundamentals Chapter 13 Controlling the Look of Your Survey
145
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.
Chapter 13 Controlling the Look of Your Survey Survey Programming Fundamentals
146
Example
Example
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]
Where LabelStyleTypesEnum are:
LabelStyleTypes Enum Description lsQuestion Style for question labels. lsCategory Style for category labels. lsBanner Style for banner labels. lsError Style for error labels. lsNavigation Style for navigation labels. lsTitle Style for title labels.
The code below will make all question text to have a font size of 24.
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
Routing(Web) IOM.DefaultStyles.Navigation.BgColor = "#0099FF" AmtSpenYr.Ask() End Routing
The code above will create a blue background color on the navigation buttons.
Survey Programming Fundamentals Chapter 13 Controlling the Look of Your Survey
147
Example
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]
Where the QuestionStyleTypesEnums are:
QuestionStyleTypes Enum Description qsInfo Information items. qsLong Long (integer) questions qsText Text questions qsCategorical Categorical Questions qsDate Date questions qsDouble Double (real) questions qsBoolean Boolean questions qsLoopCategorical Categorical loops. qsLoopNumeric Numeric loops. qsCompound Compound questions qsBlock Block questions qsPage Multiple question page items. qsOther Automatic Other Specify questions.
For example the following can be used to make all "other specify" textboxes a certain size.
Routing(Web) IOM.DefaultStyles.Questions[QuestionStyleTypes.qsOther].Style.Width = 220 HotelChainStayed.Ask() End Routing
Chapter 13 Controlling the Look of Your Survey Survey Programming Fundamentals
148
Example
Example
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 question‐specific 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.
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.
Metadata (en‐US, Question, Label) Souvenirs "Which of the following souvenirs do you prefer to purchase when on holiday or vacation?" categorical [1..1] { SelectOne "Select One" { Clothing , Hats, Postcards , SnowGlobes "Snow Globes" } }; End Metadata
Survey Programming Fundamentals Chapter 13 Controlling the Look of Your Survey
149
Example
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.
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:
To change to a single line format:
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
Chapter 13 Controlling the Look of Your Survey Survey Programming Fundamentals
150
Example
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.
Metadata (en‐US, Question, Label) HappyLastTravel "Choose the image below that indicates how happy you were the LAST time you traveled." style(Orientation = Row) categorical [1..1] { VeryHappy "Very happy" style(Image = "VeryHappy.gif", Control(Type = "Button")), SlightlyHappy "Slightly happy" style(Image = "SlightlyHappy.gif", Control(Type = "Button")), NeitherNor "Neither happy nor unhappy" style(Image = "NeitherNor.gif", Control(Type = "Button")), SlightlyUnhappy "Slightly unhappy" style(Image = "SlightlyUnhappy.gif", Control(Type = "Button")), VeryUnhappy "Very unhappy" style(Image = "VeryUnhappy.gif", Control(Type = "Button")) }; End Metadata
The code above will produce the following question:
Survey Programming Fundamentals Chapter 13 Controlling the Look of Your Survey
151
Custom Controls Custom controls are a type of sub‐template 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
Chapter 13 Controlling the Look of Your Survey Survey Programming Fundamentals
152
Example
TravelItem "From the list below, which <b>one</b> item would you most want to bring 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.
Final Thoughts on Formatting When people are faced with so many places to apply formatting, they may be confused by what formatting should go where. One issue you should take into consideration when deciding where to apply specific looks of your survey is system efficiency vs. ease of use. Let’s say for example that you want all the surveys to have a default font of "Tahoma"; where is the best place to declare this? Since you want this applied to everything, ideally you should put this in the template or associated CSS file since it is at the highest level. In this way you get the correct font without having to declare anything in your survey. Also if you later change your style you will not need to update any scripts. (Not to mention mrInterview will not have to process that style detail.) And you can still use the styles to override the templates when necessary.
Survey Programming Fundamentals Chapter 13 Controlling the Look of Your Survey
153
Exercise Open the Meals.mdd file and Save as MealsWithStyle.mdd
• Add the template, Verge_Layout.htm file to the document
• The Calories grid has numeric responses; make a box size of 50 for those numeric questions.
• Change the HealthComm box size to height of 100 and width of 550.
As time allows format all the grids to have the following look:
Hints:
• Size of columns = 90px
• Color of rating scale text = #BB342B
• Color of alternate rows = #B8B8B8
• Borders are solid, 1 width, and color of #B8B8B8
Chapter 13 Controlling the Look of Your Survey Survey Programming Fundamentals
154
Survey Pr
Example
ChapteYou may you wantpositive o
DisplayYou can d
{
Item Name
rogramming
er 14 Teneed to havet to list how mor negative ra
ying Respodisplay the an
{#Name}
DescriptioName of th
Souveor vac cate { Cl H Po Sn } ran WhySotext;
Fundamental
ext Substite text within ymany answerating to a pre
onses to Pnswers to pre
n he question t
nirs "Which oation?" egorical [1..1]
lothing , ats, ostcards, nowGlobes "Sn;
ouvenir "Why
In this c
Display anthe text of
Displayingwithin a gr
Insert textcontrolled
ls
tutions anyour survey ts were chosevious questio
Previous Qevious questio
hat contains
of the followi
Snow Globes"
y do you pref
hapter w
answer to a pf the survey
answers to prrid
t into the meta in the routing
Chapt
nd Text Hhat changes wn at a previouon (“Why did
Questions ons in the sur
the response
ng souvenirs
"
er to purchas
we will:
revious questi
revious questio
adata that will g section
ter 14 Text S
Headings with the respus question oyou give the
rvey within an
e you want to
do you prefe
se {#Souvenir
on in
ons
be
ubstitutions a
ponses given. or to have texproduct a po
ny of the text
display
er to purchase
rs} when on h
and Text Hea
For instancext that reflectositive rating?
in the metad
e when on ho
oliday or vac
dings
155
e, if s a ?”).
data.
oliday
ation?"
Chapter 14 Text Substitutions and Text Headings Survey Programming Fundamentals
156
Example
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.
Metadata (en‐US, Question, Label) InterestinLocation "Please rate the following travel destinations on your interest in visiting the location." loop { Aruba , Bermuda, Florida, Hawaii, Fiji, CostaRica "Costa Rica", Thailand "Thailand" } fields ( Rating "Please rate {@} on your interest in visiting." Categorical [1] { ExtremelyInterested "Extremely Interested", SomewhatInterested "Somewhat Interested", Neutral , SomewhatDisinterested "Somewhat Disinterested" , ExtremelyDisinterested "Extremely Disinterested" }; ) expand grid; End Metadata
Survey Programming Fundamentals Chapter 14 Text Substitutions and Text Headings
157
Example
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.
Metadata (en‐US, Question, Label) InterestInLocation "Please rate the following travel destinations on your interest in visiting the location." Loop { Aruba , Bermuda, Florida, Hawaii, Fiji, CostaRica "Costa Rica", Thailand "Thailand" } fields ( Rating "Please rate {@} on your interest in visiting." categorical { ExtremelyInterested "Extremely Interested", SomewhatInterested "Somewhat Interested", Neutral , SomewhatDisinterested "Somewhat Disinterested , ExtremelyDisinterested "Extremely Disinterested" }; ) expand grid; WhyAruba "Why did you rate Aruba {#\.InterestinLocation[{Aruba}].Rating}?" text; End Metadata
Chapter 14 Text Substitutions and Text Headings Survey Programming Fundamentals
158
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 re‐displaying 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.
Metadata (en‐US, Question, Label) Name "Text {Marker}" type parameters;
End Metadata
Routing(Web)
Name.Label.Inserts[ "Marker" ].Text = Value
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 ["Marker"]
Represents the variable you created to be the placeholder for the text you want 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.
Survey Programming Fundamentals Chapter 14 Text Substitutions and Text Headings
159
Example
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.
Metadata (en‐US, Question, Label) HotelChainStayed "Choose the hotel chains you have stayed at this past year." categorical [1..] { InterContinental , Cendant, Marriott, Accor, Choice, Hilton, OtherHotel "Other Hotel Chain" other, DontKnow "Don’t Remember" DK, Refused "Prefer not to Answer" REF }; ExplainChains "Please give a brief explanation why you chose to stay at {Chain} as opposed to others in the past year." text [1..]; OneChain "this chain" info; Chains "these chains" info; 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
Chapter 14 Text Substitutions and Text Headings Survey Programming Fundamentals
160
Example
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.
Metadata (en‐US, Question, Label) HotelChainStayed "Choose the hotel chains you have stayed at this past year." categorical [1..] { InterContinental , Cendant, Marriott, Accor, Choice, Hilton, OtherHotel "Other Hotel Chain" other, DontKnow "Don’t Remember" DK, Refused "Prefer not to Answer" REF }; ExplainChains "Please give a brief explanation why you chose to stay at {Chain} as opposed to others in the past year." text [1..]; OneChain "this chain" info; Chains "these chains" info; 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
Survey Programming Fundamentals Chapter 14 Text Substitutions and Text Headings
161
Example
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.
Metadata (en‐US, Question, Label) TypeAccom "At what type of accommodations did you stay?" categorical [1..1] { Hotels , Motels, BedBreakfast "Bed and Breakfasts", Hostels , Resorts , OtherAccom "Other Accommodations" other }; HowFreqStay "How frequently do you stay at {Accom}?" categorical [1..1] { VeryFreqently "Very Frequently" , SomewhatFreqently "Somewhat Frequently", Rarely , FirstTime "This was the first time" }; End Metadata Routing (Web) TypeAccom.Ask() if TypeAccom = {OtherAccom} then HowFreqStay.Label.Inserts["Accom"]=TypeAccom.OtherAccom else HowFreqStay.Label.Inserts["Accom"]=TypeAccom.Response.Label end if HowFreqStay.Ask() End Routing
Chapter 14 Text Substitutions and Text Headings Survey Programming Fundamentals
162
Example
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:
To add a new heading:
Name.Banners.AddNew("BannerName", InfoName.Label)
To reuse a banner with different text:
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, NewInfoName.Label
Name of the info item holding the text you wish to display. You can also choose 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.
Metadata (en‐US, Question, Label) HotelChainStayed "Choose the hotel chains you have stayed at this past year." categorical [1..] { InterContinental , Cendant, Marriott, Accor, Choice, Hilton, OtherHotel "Other Hotel Chain" Other, DontKnow "Don’t Remember" DK, Refused "Prefer not to Answer" REF };
Survey Programming Fundamentals Chapter 14 Text Substitutions and Text Headings
163
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 "Don’t Remember" DK, Refused "Prefer not to Answer" REF }; InterestinLocation "Please rate the following travel destinations on your interest in visiting the location." loop { Aruba, Bermuda, Florida, Hawaii, Fiji, CostaRica, Thailand } fields ( Rating "Please rate {@} on your interest in visiting" categorical [1..1] { ExtremelyInterested "Extremely Interested", SomewhatInterested "Somewhat Interested", Neutral "Neutral", SomewhatDisinterested "Somewhat Disinterested ", ExtremelyDisinterested "Extremely Disinterested" }; ) expand grid; HotelText "Hotel Questions" info; DestinationText "Destination Questions" info; End Metadata
Chapter 14 Text Substitutions and Text Headings Survey Programming Fundamentals
164
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:
Survey Pr
ChapteTo obtainmay wanquestion
As stateddo 2 thin
• S
• P
Technicarespondefeature wthey couthe respo
rogramming
er 15 Enn accurate dant to either prand continue
d above, mrIngs:
Set the MustA
Provide mrInt
lly, there is stent will not hawould be a texld simply choonse as the p
Fundamental
nhancing Sta, by defaultre‐set informae with the sur
nterview requ
Answer prope
terview with a
till an answerave to responxt question foose the Next re‐determine
In this c
Pre‐assign t
Understandto not give
Allow for an
ls
Survey Flt mrInterviewation into quervey.
uires a respon
erty to False
a default answ
r for each quend to every quor optional cobutton to co
ed default.
hapter w
the initial answe
d the property than answer to a q
n answer to be t
ow w requires a reestions or allo
nse to each qu
wer when the
estion when yuestion whenomments. If ontinue with t
we will:
ers to questions.
hat allows respoquestion
the default respo
Chap
esponse to eaow responde
uestion. To o
e respondent
you look at yon it isn’t necesthe respondethe survey wh
ondents
onse
pter 15 Enha
ach questionnts to not ans
override this o
t does not cho
our data, howssary. A goodent did not hahile mrIntervi
ancing Survey
. At times, yoswer the
option, you m
oose a respon
wever the d use of this ave a commeew will recor
y Flow
165
ou
must
nse.
ent, rd
Chapter 15 Enhancing Survey Flow Survey Programming Fundamentals
166
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 pre‐assigned 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.)
Survey Programming Fundamentals Chapter 15 Enhancing Survey Flow
167
Example
The following is an example of adding default responses in the metadata.
TravelSpent "In the past year, approximately how many much did you spend in each 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); LeisureTravel "Leisure Travel" long [0 .. ] defaultanswer(0) ) expand grid;
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)”.
Chapter 15 Enhancing Survey Flow Survey Programming Fundamentals
168
Example
Example
You can even set default values for categorical questions:
Metadata (en‐US, Question, Label) Age "To which of the following age categories do you belong?" categorical [1..1] { Under18 "Under 18", _18to34 "18 to 34", _35to54 "35 to 54", _55plus "55 and over", Refused "Prefer not to Answer" REF } defaultanswer ( {Refused} );
End Metadata
In the above example if the respondent doesn’t answer the question, when they click the Next button the answer will be recorded as Refused.
Another way to set this default would be in the routing section:
Routing(Web)
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.
Survey Programming Fundamentals Chapter 15 Enhancing Survey Flow
169
Example
Hidden default responses The keyword NA is the assumed value for the property defaultanswer. If you have:
• 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.
Metadata (en‐US, Question, Label) AddComments "Please provide us with any additional comments."
text
codes( { NoAnswer "No Comments" NA } );
End Metadata
Routing(Web)
AddComments.MustAnswer=False
AddComments.Ask()
End Routing
The screen displays:
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.
Chapter 15 Enhancing Survey Flow Survey Programming Fundamentals
170
Example
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 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); LeisureTravel "Leisure Travel" long [0 .. ] initialanswer(0) ) expand grid;
This would be what the screen would look like when the respondent first sees the question:
Survey Programming Fundamentals Chapter 15 Enhancing Survey Flow
171
Example
The code in the routing section to set the initial value for this complex question type would be:
Metadata (en‐US, Question, Label) TravelSpent "In the past year, approximately how many much did you spend in each 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 .. ]; LeisureTravel "Leisure Travel" long [0 .. ] ) 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 re‐set again if they have changed the values. If you would like to always re‐set the values, then use the QuestionName.Response.Value = response.
Chapter 15 Enhancing Survey Flow Survey Programming Fundamentals
172
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.”
Prefer not to Answer
• 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.)
Survey Pr
ChapteThere maquestioncan contr
Each stan
MessageMissingA
NotNum
NotInteg
NotDate
NotInRan
NotSingle
TooFewA
rogramming
er 16 Cuay be times w, or your orgarol the text of
ndard error m
e Name Answer
eric
ger
nge
eAnswer
Answers
Fundamental
ustomizingwhen the stananization has f the standar
message has a
Message TexMissing answ
Answer '{ANnumeric. Answer '{ANan integer vaAnswer '{ANvalid date. Answer '{ANin range '{RAOnly one anallowed. There are toat least {MINrequired.
In this c
Learn the standard e
Customizewithin you
Change thsurveys
ls
g the Stanndard error mstandards fod error messa
a name associ
xt wer(s).
NSWER}' is no
NSWER}' is noalue. NSWER}' is no
NSWER}' is noANGE}'. swer is
oo few answeNANSWERS} a
hapter w
keywords assoerror messages
e the text of theur script for a s
e standard err
Chapter
ndard Errmessages are nr the error teages.
iated with it a
When dThe resquestioanswernot ent
t The reslong (in
t The resinteger
t a The resdate.
t The resspecifieMore thchoice r
rs, are
The numchoice lrequire
we will:
ociated with ths
e error messagpecific questio
ror message fo
r 16 Customi
ror Messanot descriptivext that are di
and is listed in
displayed pondent clickn, and the sc. Also applieser answers inponse cannotteger) or douponse is a nuvalue. ponse cannot
ponse does ned for the quehan one resporesponse list.mber of respoist is less thad for the que
e
ges on
r all
zing the Stan
ages ve enough forifferent than
n the table be
ks Next withoript does not s when the ren all cells of a t be converteuble (decimalmeric value,
t be converte
not fall withinestion. onse was cho onses chosenn the minimuestion.
dard Error M
r a specific the defaults.
elow.
out answeringspecify a defspondent doegrid. ed into a valid), as appropribut is not an
ed into a valid
the range
osen from a si
from a multium number
essages
173
You
g the fault es
d iate.
d
ingle
iple
Chapter 16 Customizing the Standard Error Messages Survey Program
174
Message Name Message Text When displayed TooManyAnswers There are too many answers,
only {MAXANSWERS} are allowed.
The number of responses chosen from a multiple choice list is greater than the maximum number allowed for the question.
CannotCombine Answer '{ANSWER}' ({CATEGORY}) cannot be combined with other answers.
More than one response was selected, one of which was marked as exclusive.
OtherNotSelected Answer '{ANSWER}' ({CATEGORY}) has a response but is not selected.
The 'Other' response box has text filled in, but the Other response has not been selected.
InvalidText Answer '{ANSWER}' is not valid. A text response is not in the format specified in the question; for example, not a valid telephone number.
TooLittleText The answer does not have enough text, current length is '{LENGTH}', minimum is '{MINLENGTH}'.
The number of characters in a text response is less than the minimum specified in the question.
TooMuchText The answer has too much text, current length is '{LENGTH}', maximum is '{MAXLENGTH}'.
The number of characters in a text response is greater that the maximum specified in the question.
PlayerNavigationDisabled You have used the browser buttons, please use the Next/Previous buttons below.
The respondent used the browser's navigation buttons when the project does not allow this.
The above table is listed in the DDL at this link: DDL.chm::/interviewscripting_errors_standard.htm
You can change the messages associated with the errors in 3 ways:
• Globally for all mrInterview projects
• For all questions within a metadata file
• For a specific question
Survey Programming Fundamentals Chapter 16 Customizing the Standard Error Messages
175
Example
Global changes to error messages To change the wording of error messages globally for all projects, they are contained in the StandardTexts.mdd file on the mrInterview server. Please note that this file holds the translations for the error messages as well. If you produce multi‐lingual studies, you will need to translate the new messages to any additional languages necessary.
Error messages changes for a specific metadata file To replace the error message text for the whole script, include a StandardTexts block with an Errors block in the metadata as shown below.
StandardTexts block fields (
Errors block fields ( MessageName1 "Text 1" info; MessageNamen "Textn" info; ... );
);
Item Description MessageName1, MessageNamen
Name of the standard message as shown in the table previously.
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.
Metadata(en‐US, Question, Label) StandardTexts "StandardTexts" block fields ( Errors "Errors" block fields ( Missinganswer "Please answer the question." info; ); );
End Metadata
Chapter 16 Customizing the Standard Error Messages Survey Program
176
If a respondent did not choose an answer for any question within the survey, they would see:
Error messages changes for a specific question Changing the error message for a specific question is very similar to the method for every question within the survey. The difference is that the StandardText block must be added to a helper field attached to the question:
Metadata(en‐US, Question, Label)
QuestionName "text" questiontype helperfields ( StandardTexts "StandardTexts" block fields ( Errors "Errors" block fields ( MessageName1 "Text 1" info; MessageNamen "Text n" info; ... ); ); );
Item Description helperfields Keyword used to store additional information for a field/question MessageName1, MessageNamen
Name of the standard error message.
Text1, Textn Represents the replacement message text
Survey Programming Fundamentals Chapter 16 Customizing the Standard Error Messages
177
Example
Customizing the error message You can customize the wording of the message by using some of the substitution markers listed in the table below. Enclose the markers in curly brackets when inserting into the error text.
Substitution Marker Description ANSWER The respondent's answer. RANGE The valid answer range for the question as defined in the metadata section. QUESTION The question name. QUESTION_NUMBER The question number. LENGTH The length of the response text. MINLENGTH The minimum length for a text response. MAXLENGTH The maximum length for a text response. MINANSWERS The minimum number of answers that must be chosen from a multiple choice
list. MAXANSWERS The maximum number of answers that may be chosen from a multiple choice
list. CATEGORY The text of a single multiple choice response. ERROR The error message associated with an internal error.
This example will make the respondent’s error message clearer in its meaning.
DaysTravelYr "On average how many days per year do you travel for business or leisure?" 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; ); ); );
Chapter 16 Customizing the Standard Error Messages Survey Program
178
When the respondent’s answer is out of the range, it will display a new error message:
Survey Pr
ChapteWith Dimwill help
DefinitA functiorelativelyprogram
There are
• R
• E
• Da
• I
The parts
• A
• P
• A
Let’s look
rogramming
er 17 Fumensions Scripyou to do cer
tion of Funon or subrouty independenming languag
e several adva
Reducing the
Enabling reus
Decomposingadd/subtract
mproved rea
s of a function
A body of cod
Parameters th
A value that is
k at some ver
Fundamental
unctions &pting (and othrtain actions,
nctions antine is a sectiont of the remages, not speci
antages to us
duplication o
e of code acr
complex profunctionality
dability of a p
n or subrouti
de to be execu
hat are passe
s returned to
ry basic exam
In this c
Define Fun
Learn howSubroutine
See exampin Dimensi
ls
& Subrouther programmsuch as valid
nd Subrouton of code wiaining script. fic to Dimens
sing functions
of code in a pr
oss multiple s
oblems into sias needed)
program
ne may includ
uted when th
d to the subr
the point wh
ples to under
hapter w
nctions and Su
w to write Funces in Dimensio
ples of Functioions Scripting
tines ming languagdate question
tines ithin a script wThese are tesions Scripting
s or subroutin
rogram
scripts
mpler pieces
de:
e subroutine
outine from t
here the call o
rstand the co
we will:
broutines
tions and ons Scripting
ns and Subrou
Chapt
es), you can c logic or spec
which perforrms that are g.
nes, including
s (this makes t
is called
the point whe
occurs (functi
oncept of func
utines
ter 17 Functio
create re‐usecific formattin
ms a specific common to o
g:
them easier t
ere it is called
on only)
ctions and su
ons & Subrou
eable code thang issues.
task and is other
to maintain a
d
broutines.
utines
179
at
nd
Chapter 17 Functions & Subroutines Survey Programming Fundamentals
180
Subroutine To define a subroutine:
Sub Name(var1, var2, varN)
Statements
End Sub
To call (use) a subroutine:
Name(parameter1, parameter2, parameterN)
Item Description Sub End Sub
Marks the start and end of a subroutine
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, parameter2, parameter3
Represents the actual parameters that are passed to the subroutine. The order of these parameters will match up with the variables on the subroutine (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:
Survey Programming Fundamentals Chapter 17 Functions & Subroutines
181
Example
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 = "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
Chapter 17 Functions & Subroutines Survey Programming Fundamentals
182
The previous code would produce the following look:
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 subroutine’s structure and give it a name that is easily recognizable:
Sub GridStyle1()
End Sub
Survey Programming Fundamentals Chapter 17 Functions & Subroutines
183
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:
Sub GridStyle1 (QuestionName, ColHeadWid, ColWid, ColWrap)
End Sub
QuestionName, ColHeadWid, ColWid, and ColWrap are similar to temporary variables, so the names can be anything you like.
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.
Sub GridStyle1 (QuestionName, ColHeadWid, ColWid, ColWrap)
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:
Sub GridStyle1 (QuestionName, ColHeadWid, ColWid, ColWrap)
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
Chapter 17 Functions & Subroutines Survey Programming Fundamentals
184
Example
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) GridStyle1(AirlineRating,"300px" , "70px" ,true) AirlineRating.Ask() GridStyle1(InterestinLocation, "120px" , "90px" ,true) InterestinLocation.Ask() Sub GridStyle1 (QuestionName, ColHeadWid, ColWid, ColWrap) 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 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.
Function Name(var1, var2, varN)
Statements
Name = value
End Function
To call (use) a function:
Name(parameter1, parameter2, parameterN)
Survey Programming Fundamentals Chapter 17 Functions & Subroutines
185
Item Description Function End Function
Marks the start and end of a 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, parameter2, parameter3
Represents the actual parameters that are passed to the function. The order of these parameters will match up with the variables on the function (example: parameter1 is the information that will be inserted in the function represented as var1)
Chapter 17 Functions & Subroutines Survey Programming Fundamentals
186
Example
Suppose we had a shared list of travel agencies that had 30 categories:
Metadata(en‐US, Question, Label) Agencylst "" define { Agency1 "Travel Agency 1", Agency2 "Travel Agency 2", Agency3 "Travel Agency 3", Agency4 "Travel Agency 4", … Agency30 "Travel Agency 30" }; AgencyHeardOf "Which of the following travel agencies have you heard of?" categorical { use AgencyLst }; 'Create a filter for AgencyUse to be the responses of AgencyHeardOf AgencyUse "Of those you were aware of, which travel agencies would you consider using to book your travel?" categorical { use AgencyLst }; End Metadata 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
Survey Programming Fundamentals Chapter 17 Functions & Subroutines
187
Example
Example
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 built‐in function, int(), which returns the integer portion of a number.
Routing(Web) agencyheardof.Style.Columns=3 agencyheardof.Ask() agencyuse.Categories.Filter=agencyheardof Dim Actual, IntegerValue, DecimalValue Actual = CDouble(AgencyHeardof.AnswerCount())/10 IntegerValue = int(AgencyHeardof.AnswerCount()/10) DecimalValue = Actual ‐ IntegerValue If DecimalValue > 0 Then agencyuse.Style.Columns = IntegerValue + 1 Else agencyuse.Style.Columns = IntegerValue End If AgencyUse.Ask() 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) 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 If DecimalValue > 0 then ForceCols = IntegerValue + 1 Else ForceCols = IntegerValue End If End Function End Routing
Chapter 17 Functions & Subroutines Survey Programming Fundamentals
188
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 re‐useable with the concepts learned in this chapter. It would be helpful to have a piece of re‐usable 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
Survey Pr
ChapteIn the lasunique fuconcepts
ValidatYou can ispecific psmall am
N
V
Item Name
"Text" text Validatioexpressio
rogramming
er 18 Vast chapter weunction that as that will help
ting Text Qinclude statempattern. Reguount of code
Name "Text"
Validation(" e
DescrMeta
Text aQuest
on Propeon Regul
Fundamental
alidation discussed thallows you top us validate
Question Pments withinular Expressio.
text
expression");
ription data item na
associated wition type. Merty keyword lar Expression
In this c
Validate a
Understanlogic
Create cusDimension
ls
e concepts o easily validatthe logic of th
Patterns the metadatons allow you
me
ith the item ust be text toto allow you n syntax
hapter w
text question
nd how to add
stom logic withns validation fu
f subroutineste logic in quehe survey.
ta that will ch to do create
o add a regulato add a regu
we will:
to follow a pat
errors for cust
h the use of unctions
s and functionestions. We w
eck a text fie very complic
ar expressionular expressio
ttern
tom
Chap
ns. Dimensiowill also look
ld to see if it cated match a
on
pter 18 Valid
ns scripting hat additional
matches a algorithms wi
dation
189
has a l
ith a
Chapter 18 Validation Survey Programming Fundamentals
190
Example
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 (a‐z, A‐Z, 0‐9) \W Matches any nonword character. \d Matches any decimal digit. Equivalent to \p{Nd} for Unicode and [0‐9] for non‐Unicode,
ECMAScript behavior. \D Matches any nondigit. Equivalent to \P{Nd} for Unicode and [^0‐9] for non‐Unicode,
ECMAScript behavior.
The DDL does reference regular expressions: DDL.chm::/aliasmap_regularexpressions.htm however, there are also many references on the web as well, such as: http://en.wikipedia.org/wiki/Regular_expressions and http://regexlib.com/cheatsheet.aspx .
The following example will check the length of the phone number and also if it follows the specific pattern with 2 dashes.
Phone "Please enter your 10‐digit 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.
Survey Programming Fundamentals Chapter 18 Validation
191
Example
The next example is more flexible, allowing you to check an email address to ensure it contains an @ sign.
Email "Email:" 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 (a‐z), then a mandatory @ sign, followed by a dash, period or any word character.
Chapter 18 Validation Survey Programming Fundamentals
192
Checking Custom Logic There are many times you will need to do logic checks within your survey that are not covered by the standard error messages. The most efficient way to achieve this is through custom validation. The concept is a special type of function that is tied directly to a question.
Function functionname(Question, IOM, Attempt)
Statements
functionname = True
Statements
functionname = False
End Function
Item Description Function End Function
Defines the start and end of the 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 False
Values that the Dimensions custom validation function must pass back. These special functions must set the functionname to true or false
Survey Programming Fundamentals Chapter 18 Validation
193
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.)
Adding custom errors In the next examples, we will be creating customized logic that may require you to have the respondent re‐answer the question. To do that action, you need to add your own error message. You can create errors that have the same properties as the standard error messages. In the routing section you would add:
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
Chapter 18 Validation Survey Programming Fundamentals
194
Example
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%.
Metadata(en‐US, Question, Label) Activities define { Train "On a train/train station", Airplane "In an airplane/airport", Vehicle "In a Vehicle driving or riding", Subway "Subway System", Walk "Walking", OtherMode "Other" }; 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; ErrorGridAddto100 "Please check your responses. Responses should add up to 100." info; End Metadata
Survey Programming Fundamentals Chapter 18 Validation
195
Example
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) IOM.LayoutTemplate = "Card_Blue_TopAndBottomErrors.htm" PercActivity.Validation.Function = "ValidateGrid100" PercActivity.Ask() Function ValidateGrid100(Question, IOM,Attempt) Dim category Dim total If attempt <= 3 Then For Each category in Question total = total + category.Item[0].Response.Value Next If total <> 100 Then Question.Errors.AddNew("ErrorGrid", IOM.Questions.ErrorGridAddto100.Label) ValidateGrid100 = False Else ValidateGrid100 = True End If End If End Function End Routing
Chapter 18 Validation Survey Programming Fundamentals
196
Example
Let’s 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 question’s response within the function.
Metadata(en‐US, Question, Label) HrsTravelMode "Thinking of your travel over the last year, approximately how many hours did you spend using some type of transportation?" long [0..8760]; 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; ErrorGridAddtohrs "Please check your responses. Responses should add up to {#HrsTravelMode}." info; End Metadata
Survey Programming Fundamentals Chapter 18 Validation
197
Example
Again, the routing section is where the validation happens. Notice the reference to the additional question with the “IOM.Questions” preceding it.
Routing(Web) IOM.LayoutTemplate = "Card_Blue_TopAndBottomErrors.htm" HrsTravelMode.Ask() HrsActivity.Validation.Function = "ValidateGridEqualDependentQ" HrsActivity.Ask() Function ValidateGridEqualDependentQ (Question, IOM,Attempt) Dim category Dim total If attempt <= 3 Then For Each category in Question total = total + category.Item[0].Response.Value Next If total <> IOM.Questions.HrsTravelMode Then Question.Errors.AddNew("ErrorGrid", IOM.Questions. ErrorGridAddtohrs.Label) ValidateGridEqualDependentQ = False Else ValidateGridEqualDependentQ = True End If End if End Function End Routing
Chapter 18 Validation Survey Programming Fundamentals
198
The above works nicely, however it is very specific to the question. The line:
If total <> IOM.Questions.HrsTravelMode Then
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.
Adding custom properties to metadata Custom properties can be any additional information attached to a metadata item. One basic way to add custom properties is in the metadata section:
Name "text" [property] type
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. Let’s 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.
Survey Programming Fundamentals Chapter 18 Validation
199
Example
Metadata(en‐US, Question, Label) HrsTravelMode "Thinking of your travel over the last year, approximately how many hours did you spend using some type of transportation? " long [0..8760]; 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; ErrorGridAddtohrs "Please check your responses. Responses should add up to {#HrsTravelMode}." info; End Metadata
Chapter 18 Validation Survey Programming Fundamentals
200
Example
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) IOM.LayoutTemplate = "Card_Blue_TopAndBottomErrors.htm" HrsTravelMode.Ask() HrsActivity.Validation.Function = "ValidateGridEqualDependentQ" HrsActivity.Ask() Function ValidateGridEqualDependentQ (Question, IOM,Attempt) Dim category Dim total If attempt <= 3 Then For Each category in Question total = total + category.Item[0].Response Next If total <> IOM.Questions[Question.Properties["dependentQ"]] Then 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 re‐used in different projects. You can see how a library of custom validations will speed the programming process over time.
Survey Pr
ChapteThe compmultiple denominalso be d
DefininIn essenccategoriethe same
C
{
(
Q
Q
)
Item Compoun"Text" compouncategorie
fields QuestionQuestion
rogramming
er 19 Copound type hquestions onator of a shaone for web‐
ng Compouce, a compoues. Think of ae page horizo
CompoundNa
{ Categories }
Question1;
QuestionN;
;
DendName Un
Opnd Kees Re
YoPr
n1, nN
Ca
Fundamental
mpound helps you to a the same scrred list of cat‐based studie
und Questnd is simply ma compound ntally. The sy
ame "Text" c
} fields
escription nique name fptional Text teyword to creepresents theou may use a recedes the qategorical que
This ch
The definit
Validating
Differencequestions
ls
Questionachieve a specreen horizonttegories. Thiss.
tions multiple quesquestion as ayntax for a co
compound
for the compoto display acreate a compoe categories foshared list he
questions withestions and c
hapter co
tion of a comp
compound qu
es between loo
ns cial look to yotally. These qs is traditiona
stions (includia container foompound is as
ound metadaoss the top oound metadator which the ere if you wishin the compategorical loo
overs:
pound question
uestions
ops and compo
Cha
our questionnquestions mully used in pa
ing grids) whior other quests follows:
ta item f the screen ota item questions ansh. ound item ops that you w
n
ound
apter 19 Com
naire when yost have the coaper‐based su
ich all share ations you wis
of the compo
d loops are to
want to displ
mpound Ques
ou wish to disommon urveys, but ca
a common listh to display o
ound question
o be asked.
ay side by sid
stions
201
splay
an
t of on
n
de.
Chapter 19 Compound Questions Survey Programming Fundamentals
202
Suppose we want to create the following look for our survey:
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.
Survey Programming Fundamentals Chapter 19 Compound Questions
203
Example
Metadata(en‐US, Question, Label) Airlines "" define { United, Delta , BritishAirways "British Airways" , Luftansa "Luftansa" }; 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
Chapter 19 Compound Questions Survey Programming Fundamentals
204
Example
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.
Validating a compound question Validating compound questions can prove challenging for beginner programmers. However, with the skills taught in the previous sections of validations, you are on your way to validating complex compound questions as well. Here is a simplified version of the example above. This example only includes the questions FlownBefore and Trips6Mo_Loop.
Metadata(en‐US, Question, Label) Airlines define { United, Delta, BritishAirways "British Airways , Luftansa }; 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; ); CompoundError "Missing answers, please try again." info; End Metadata
Survey Programming Fundamentals Chapter 19 Compound Questions
205
Example
The logic you will need to check for will be:
• If FlownBefore is chosen, then Trips6MoLoop must be answered
• If FlownBefore is not chosen, then Trips6MoLoop must be null
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) 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 If (Question.Item[0].ContainsAny(Cat) And Question.Item[1].Item[Cat].Item[0] = Null ) _ Or (NOT (Question.item[0].ContainsAny(Cat)) And _ Question.Item[1].Item[Cat].Item[0] Is Not Null) Then ValidateSimpleCompound = False End If Next If ValidateSimpleCompound = False Then Question.Errors.AddNew("CompoundError",IOM.Questions.CompoundError.Label) End If End Function End Routing
Chapter 19 Compound Questions Survey Programming Fundamentals
206
Compound vs. Loop You may have noticed similarities between compound questions and loops that have multiple different types of questions. There are a few main differences between compounds and loops to be aware of:
• 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
Survey Pr
ChaptemrIntervto enhanwould be
Using samresponde
• Dp
• Cr
To refere
I
Item SampleFi
rogramming
er 20 Woiew allows yoce the surveye to customize
mple manageents for use d
Displaying infoparticipating.”
Creating a querespondent’s
ence informat
OM.SampleR
Desield Rep
you
Fundamental
orking wiou to access iy experience e the intervie
ement allows during the inte
ormation hel”)
estion to holdanswers.
tion stored in
Record.Item["
scription presents the nu wish to retri
In this c
Retrieve ininto the Di
Send inforscript to th
Use a test to check y
ls
ith Samplnformation yand/or data. ew screens ba
you the optioerview either
d in the table
d the sample
n the sample t
" sampleField
name of the fieve.
hapter w
nformation froimensions Scri
rmation from the sample tabl
sample recordour Dimension
le ou have abou One scenarioased on who i
on to bring adr by:
e to the respo
information s
table about th
d "]
field in the SQ
we will:
m the sample pt
he Dimensionse
d locally in mrSns script
Ch
ut your potenos for using tis currently ta
dditional info
ondent (“Hello
so it is easily
he current re
QL database t
table
s
Studio
apter 20 Wo
ntial respondehe additionalaking the inte
rmation abou
o, Bob. Than
analyzed with
spondent:
that holds the
orking with Sa
ents and use l information erview.
ut the
k you for
h the
e information
ample
207
this
Chapter 20 Working with Sample Survey Programming Fundamentals
208
Example
Here is an example of pulling information from a sample record into the text of a question. We are assuming the project’s sample table has a field named “TAgency” that holds the Travel Agencies used by the people in the sample.
Metadata(en‐US, Question, Label) VerifyTravelAgent "Our records indicate you have used the travel agency {Agency} in the past, is this correct?" categorical { Yes, No }; End Metadata Routing(Web) VerifyTravelAgent.Label.Inserts["Agency"].Text=IOM.SampleRecord.Item["TAgency"] VerifyTravelAgent.Ask() End Routing
If a specific respondent’s travel agency was Travel Agency XYZ, then their question will appear as shown below:
Survey Programming Fundamentals Chapter 20 Working with Sample
209
Example
Example
The next example does not display the respondent’s information, but rather stores it in a question for analysis purposes.
Metadata(en‐US, Question, Label) Region "Stores the region where they live." text; 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.
Metadata(en‐US, Question, Label) ReceiveTravelInfo "Check here if you wish to receive an email regarding travel safety." boolean; 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”.
Testing sample information within mrStudio You can easily test to see if you are correctly pulling your sample information into the script. mrStudio allows you to create a test sample record. To do this:
Access the file:
C:\Program Files\SPSS Dimensions\mrStudio\4.0.0.0\Interview\DefaultSample.xsu.
Chapter 20 Working with Sample Survey Programming Fundamentals
210
This is an XML document which mrStudio reads as a sample record by default. The default file is shown below:
Survey Programming Fundamentals Chapter 20 Working with Sample
211
Item Description <SampleRecord ID=”ID1”> </SampleRecord>
Marks the beginning and end of the samplerecord. Can only create a single record for testing within mrStudio.
<Samplefields> </SampleFields>
Marks the beginning and end of the sample fields for the record.
<SampleField> </SampleField>
Marks the beginning and end of a sample field.
<name> </name>
Tags to surround the name of the sample field
<type> </type>
Tags to surround the type of field. SQL field types are used. Smallint = 2; Int = 3; Datetime = 7; Char, Text, Ntext, or NVarchar = 8; Bit = 11
<value> </value>
Tags to surround the value you want the sample field to have.
You have the ability to create your own files and add additional Sample fields as shown below:
Chapter 20 Working with Sample Survey Programming Fundamentals
212
Example
In order to access the sample information, make sure that under
Tools – Options – Sample Management Record
you are referencing the correct .xsu file.
The example below will assume you are using the modified TravelSample.xsu with the additional field for region.
Metadata(en‐US, Question, Label) Region "Stores the region where they live." text; 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.
Survey Programming Fundamentals Chapter 20 Working with Sample
213
Example
Alternative to Sample Management to pass information into the survey If you are not using sample management, you can send out separate URL links to respondents that speak different languages. Then embed a parameter in the URL that will be passed into the script to set the language. mrInterview can pass parameters on the URL using the names I.User1 through I.User9. Then you can do the same things with these parameters that we did with sample management variables.
URL to send out: http://www.servername.com/scripts/mrIWeb.dll?I.Project=myproj&I.User1=DEU 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.
Chapter 20 Working with Sample Survey Programming Fundamentals
214
Survey Pr
Example
ChapteQuotas acriteria. Fare male
DefininTo setup
• T
• T
• T
Let’s look
Gender
In our me
rogramming
er 21 Wore a system fFor example, and 500 are
ng Survey a quota we n
The question
The targets fo
The type of qu
k at a simple
Targets Male Female
etadata sectio
MetadGende cate { M Fe }; End M
In
Fundamental
orking wifor controllingwe may be afemale.
Quotas need three ite
the quota wi
or the quota.
uota
example of m
500 500
on we should
data(en‐US, Qer "Are you..."egorical [1..1]
Male , emale
Metadata
n this ch
An overvie
How to chrouting sec
Checking a
ls
ith Quotag the numbersked to interv
ems:
ll be based on
making a quot
d have a quest
Question, Labe"
apter w
ew of the quot
eck and respoction
and changing q
s r of respondeview 1000 res
n scripted in y
ta based on th
tion for gend
el)
ill cover
a process
nd to quotas in
quotas online
Ch
ents interviewspondents w
your metadat
he responden
er:
:
n the
apter 21 Wo
wed matchingith the requir
ta section.
nt’s gender.
orking with Qu
predefined rements that
uotas
215
500
Chapter 21 Working with Quotas Survey Programming Fundamentals
216
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.
Survey Programming Fundamentals Chapter 21 Working with Quotas
217
We can now see the two gender categories with a grey box to the right of each:
Next, double‐click on one of the grey boxes to set the targets:
Chapter 21 Working with Quotas Survey Programming Fundamentals
218
Example
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. We’ll 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, let’s 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. Let’s add a message to use for informing the respondent what has happened.
Metadata(en‐US, Question, Label) Gender "Are you..." categorical [1..1] { Male , Female }; OverQuota "I'm sorry, the quota is full." info;
End Metadata
In the routing section, we will start by defining a temporary variable to hold our quota check and ask our quota question.
Survey Programming Fundamentals Chapter 21 Working with Quotas
219
Example
Example
Routing(Web)
Dim Quota_Pend_Result
Gender.Ask()
End Routing
You must make sure that you always check a quota after the respondent has answered.
Next add the quota check:
Routing(Web)
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.
Chapter 21 Working with Quotas Survey Programming Fundamentals
220
Example
Routing(Web)
Dim Quota_Pend_Result
Gender.Ask()
Quota_Pend_Result = QuotaEngine.QuotaGroups["QuotaGender"].Pend()
If Not(IsSet(Quota_Pend_Result, QuotaResultConstants.qrWasPended)) Then
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”.
Survey Programming Fundamentals Chapter 21 Working with Quotas
221
Example
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)
Dim Quota_Pend_Result
Gender.Ask()
If Not IOM.Info.IsDebug Then
Quota_Pend_Result = QuotaEngine.QuotaGroups["QuotaGender"].Pend()
If Not (IsSet(Quota_Pend_Result, QuotaResultConstants.qrWasPended)) Then
IOM.Texts.InterviewStopped = OverQuota.Label
IOM.Terminate(Signals.sigOverQuota)
End If
End If
End Routing
IOM.Info.IsDebug will be True whenever the survey is running inside mrStudio.
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
Chapter 21 Working with Quotas Survey Programming Fundamentals
222
Activation with Quotas Now that the quotas are created, you need upload the .mqd file and activate the study with special options for quotas. You can do this directly from mrStudio using Tools – Activate, or through DimensionNet.
For instructions on Activating quotas within DimensionNet, see the DDL: DDL.chm::/quota_dimnet.htm
Viewing & Changing Quotas You can view and change quota information online using the DimensionNet Quotas activity.
Each quota matrix in your survey will be a button on the left hand side of the activity page:
Survey Programming Fundamentals Chapter 21 Working with Quotas
223
Selecting a quota group will display the current quota counts:
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.
Chapter 21 Working with Quotas Survey Programming Fundamentals
224
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.
Survey Programming Fundamentals Chapter 21 Working with Quotas
225
When the All selection is chosen you can edit the targets, complete count, pending count as well as change between Normal, Over‐Quota and Counter quota types.
Chapter 21 Working with Quotas Survey Programming Fundamentals
226
Survey Pr
ChapteWhen imlanguagemulti‐ling
OverviWhen a p
• C
• U
• U
• By
Once youmrTranslspreadsh
rogramming
er 22 Cremplementing se, and then eagual studies, f
iew of Tranproject will be
Create the sur
Use mrTransla
Upload and ac
Be sure that tyou will have
u have a metaate reads theheet. Then yo
For demrTra
In t
Fundamental
eating Mustudies in diffasily add langfocusing on t
nslating Se run in multi
rvey .mdd file
ate to add tra
ctivate the re
he ErrorMessin your proje
adata file, youe metadata filou can add ad
etailed informanslate.chm::/
this chap
An overviemultiple la
Setting the
Tips for cre
ls
ultiLinguferent languauages to the he specific ta
tudies in Diple language
e in a base lan
anslations to t
evised .mdd fi
sage.mdd filect.
u can add thele and presendditional lang
mation on usin/mrtranslate_
pter we w
ew of how to eanguages
e language wit
eating multi‐lin
ual Projecges, Dimensiometadata fileasks for the su
Dimensiones, the basic s
nguage.
the metadata
ile to the proj
e has the erro
e translations nts the text ofguages as colu
ng mrTranslat_overview.htm
will cove
execute a surve
hin the script
ngual projects
Chapter 22
cts ons allows yoe. The chapteurvey program
ns teps are:
a file.
ject.
r messages tr
through the f your survey umns in mrTr
te, see the Usm
er:
ey in
Creating Mul
ou to create aer will reviewmmer.
ranslated for
product, mrTin a format sranslate .
ser’s Guide in
lti‐Lingual Pro
a survey in a bw the process
the language
Translate. similar to a
the DDL:
ojects
227
base of
es
Chapter 22 Creating Multi‐Lingual Projects Survey Programming Fundamentals
228
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:
• Choose the Metadata Explorer
• Open the Languages
Setting the language within the script To use the multi‐lingual functionality within mrInterview, you need to set the IOM.Language. You could accomplish this in many ways. Here are a few common methods:
• Create a question in which the respondent chooses the language.
• Have the language stored in a sample field and retrieve the information and set the language for the respondent.
Ask a question to collect and set the language When you do not know the preferred language of your respondent, a simple introductory question can be asked to collect the language.
Survey Programming Fundamentals Chapter 22 Creating Multi‐Lingual Projects
229
Example
Example
Metadata(en‐US, Question, Label) LanguageQ "Choose the language for this survey:" categorical [1..1] { ENU "English", DEU "German", ESN "Spanish" }; 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 3‐digit 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
Set language from a sample field variable If you already know the preferred language and you are using sample management, a field can be set in the sample table to hold the 3‐digit language code. The following example assumes your sample table has a field called SLanguage.
Routing(Web) IOM.Language = IOM.SampleRecord.Item["SLanguage"] End Routing
Chapter 22 Creating Multi‐Lingual Projects Survey Programming Fundamentals
230
Tips for creating multilingual projects Creating the scripts for multi‐lingual studies does not need to be difficult as long as you follow a few simple rules:
• 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.
Survey Pr
ChapteThis sectifor analyprocess btext for a
AlternaMany organalysis p(ExampleAnalysis mrTranslwho are actual cowith mrS
Adding A• O
• S
• C
rogramming
er 23 Adion shows hosis purposes.by adding comanalysis.
ate Text foganizations wpurposes. The: “What is yocontext. Youate and mrStunfamiliar wiode with its inStudio.
Analysis ConOpen the View
Select Contex
Choose Analy
In t
Fundamental
dditional iow the Dimen This sectionmmon statisti
or Analysiwill alter the tehe most commour gender?”u can add thistudio to view ith Dimensionnterface. Sinc
ntext with mw menu
ts
sis
this chap
Adding alt
Adding spescript
Creating fa
ls
informatisions scriptin adds optionsics and summ
s ext of the quemon method becomes “Res informationand add analns scripting toce this is a scr
mrStudio
pter we w
ernate text for
ecial statistics
actor scores fo
Cha
ion for Anng language iss to your intemary informat
estions that wis to change fespondent Ge in a few diffelysis context. o add the alteripting course
will cove
r reporting pur
into the interv
or use with stat
apter 23 Add
nalysis s not only for erview script ttion, such as t
were asked infrom questionender”). Theerent ways. T Using mrTraernate text, ae, we will focu
er:
rposes
view
tistics
itional inform
creating intethat will speetop box score
n a survey for n formats to se alternate teTwo commonanslate will als mrTranslateus on adding a
mation for An
erviews, but aed the analysies and alterna
reporting or statements ext is called ann ways are low individuae masks the analysis conte
alysis
231
also s ate
n
als
ext
Chapter 23 Additional information for Analysis Survey Programming Fundamentals
232
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.
Name "Text" categorical [min..max]
{ID1 "AltText1" factor(value),
IDn "AltTextn" factor(value) };
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.
Survey Programming Fundamentals Chapter 23 Additional information for Analysis
233
Example
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.
Metadata(en‐US, Question, Label) Age "To which of the following age categories do you belong?" categorical [1..1] { Under18 "Under 18" factor(18), _18to34 "18 to 34" factor(26), _35to54 "35 to 54" factor(45), _55plus "55 and over" factor(55), Refused "Prefer not to Answer" REF }; End Metadata
Creating Question Items for Analysis You can also add analysis elements to the questions to speed the availability of top‐line and final results. We will discuss two different methods for adding elements for Analysis, ElementTypes and Axis Expressions.
• 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.
Chapter 23 Additional information for Analysis Survey Programming Fundamentals
234
ElementTypes You use the optional elementtype keyword to create a special element in metadata for use in analysis.
Name "Text" type
{ID1 "AltText1,
IDn "AltTextn",
IDElement "AltTextElement" elementtype (typevalue)
};
Item Description Name Unique identifier for the item within your questionnaire. They must start with a
letter or underscore ( _ ) and contain only alpha‐numeric 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, AltTextn
Optional text to show the respondent instead of the name of the question. This 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.
Survey Programming Fundamentals Chapter 23 Additional information for Analysis
235
Example
Example
To find a full list of Analysis Elements, see the DDL: DDL.chm::/mrscriptmetadata_categorical.htm
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.
Metadata(en‐US, Question, Label) Age "To which of the following age categories do you belong?" Categorical [1..1] { Under18 "Under 18" factor(18), _18to34 "18 to 34" factor(26), _35to54 "35 to 54" factor(45), _55plus "55 and over" factor(55), Refused "Prefer not to Answer" REF, Mean "Mean Score" [ CalculationType = "Mean", HasNoData = true, ExcludedFromSummaries = true ] elementtype(AnalysisMean) }; End Metadata
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.
Metadata(en‐US, Question, Label) Rating5Pt define { Top2 "Positive Scores" elementtype(AnalysisCategory) expression("@ * {VS, SS}"), VS "Very Satisfied", SS "Somewhat Satisfied" , Neutral , Bot2 "Negative Scores" elementtype(AnalysisCategory) expression("@ * {SDS, VDS}"), SDS "Somewhat Dissatisfied" , VDS "Very Dissatisfied" }; End Metadata
Chapter 23 Additional information for Analysis Survey Programming Fundamentals
236
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.
Name "Text" type
{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 alpha‐numeric 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, AltTextn
Optional text to show the respondent instead of the name of the question. This 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
Survey Programming Fundamentals Chapter 23 Additional information for Analysis
237
Example
The following example will collect a long question type during the interview, but easily allow people doing analysis to view the pre‐set ranges of answers and a mean value.
Metadata(en‐US, Question, Label) HouseHold "Including yourself, how many people currently live in your household?" long [1 .. 20] axis("{ _1 'One' expression('Household = 1'), _2to3 '2‐3' expression('Household >=2 and Household <=3'), _4to6 '4‐6' expression('Household >=4 and Household <=6'), _7plus '7 and over' expression('Household >=7'), mean 'Mean' mean(household)}"); End Metadata
Tips creating analysis elements Adding analysis elements can prove beneficial for speeding the time for analysis setup. A few things to remember:
• These items can be added after live data collection, so don’t worry if you don’t 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.
Chapter 23 Additional information for Analysis Survey Programming Fundamentals
238