JavaScript in SSI Web
Top  Previous  Next

JavaScript in SSI Web

JavaScript Introduction
JavaScript Basics
Custom JavaScript Verification
SSI Web JavaScript Library
JavaScript Debugging



JavaScript Introduction

JavaScript is a scripting language that adds enhanced functionality and programming power to a web page. JavaScript code can verify that the input on a web page is correct before submitting it to the server. It can be used to do calculations on user input. Together with CSS, it can be used to change the appearance of the web page in real time. It is important to understand that JavaScript runs in the web browser, not on the server.

SSI Web makes extensive use of JavaScript. It is used to help validate responses to questions, fill in Constant Sum total boxes in real time, and to un-check select options when an "Other Specify" is chosen, etc. Most of SSI Web's system JavaScript is contained in ssi_javascriptX_X_X.js located in the graphics/system directory.

SSI Web also includes the MooTools JavaScript library. More information about this library can be found at http://www.mootools.net
.

For a complete tutorial on JavaScript see http://www.w3schools.com/js
.




JavaScript Basics

How to Include Custom JavaScript in SSI Web
Variables
Flow Control
Functions
Form Objects

How to Include Custom JavaScript in SSI Web

JavaScript can be included in an SSI Web survey almost anywhere text can be entered. For example, you could place some JavaScript code in the header of a question or as part of a response option. To include JavaScript on a page in SSI Web, you enclose JavaScript code in <script> </script> tags. For example, suppose you wanted to display a message in a pop-up box on the first page of your survey. You could place this text in Header 1 of the first question:

<script type="text/javascript">  
<!--  
 
alert("Welcome to the survey.");  
 
//-->  
</script>  

The JavaScript code between the <script> tags is executed when the page is loaded. In this case, as soon as the web page is loaded in the browser, a box pops up with the message "Welcome to the survey". Any JavaScript that needs to be available to the whole survey can be included in the HTML <head> Tag (Survey Settings, Headers and Footers).

JavaScript can also be included as an attribute of an HTML tag. For example:

<a href="#" onclick="alert('hello');">Click Here</a>  

When the link above is clicked, a message box with the message "hello" appears.

JavaScript can also be included in a separate file so that it can be accessed by multiple pages in your survey. A text file can be created containing your JavaScript code. This file can then be placed in your graphics folder and included with the following syntax:

<script type="text/javascript" src="[%GraphicsPath()%]CustomJavaScriptFile.js"></script>  

The text above should be placed in the HTML <head> Tag (Survey Settings, Headers and Footers).



Variables

Variables in JavaScript can be declared with the "var" statement. For example:

var NumDaysInWeek = 7;  
var MonthName = "March";  

After this code is executed NumDaysInWeek will contain 7 and MonthName will contain "March". Notice that quotes are used when assigning text to a variable.

To retrieve the value of a question on the current page you can use SSI Web's built-in SSI_GetValue(QuestionName) JavaScript function. Given any question name (or variable name) this function will return the value entered for that question on the current page. For example:

var Q1Value = SSI_GetValue("Q1");  
var BlueChosen = SSI_GetValue("FavColors_1");  

In the above example, the function SSI_GetValue retrieves the value for Q1 entered on the page. It is then assigned to the Q1Value variable. The next line retrieves the value for the first check box in a Select question. BlueChosen is assigned a 1 if it is checked and a 0 otherwise.

To retrieve the response to a question from a prior page and use that value in your JavaScript, you should use SSI Script in conjunction with JavaScript. For example, if NumWeeks was asked on a prior page of the survey and you wanted to use its value to do a simple calculation and display the result on the current screen, the following JavaScript could be used:

var NumDaysInWeek = 7;  
var Weeks = [%NumWeeks%];  

document.write(NumDaysInWeek * Weeks);  

Before the web page comes down to the browser the SSI Script [%NumWeeks%] is changed to the value that was entered on a prior page by the respondent. Lets assume that value was 4. The JavaScript loaded by the browser is:

var Weeks = 4;  

To load text from a prior question, use:

var Name = "[%LastName%]";  

which when it arrives at the browser would be:

var Name = "Smith";  

Arrays, which are variables that can hold a collection of items, are also available:

var ItemList = [1,2,3,4,5,6,7];  
document.write(ItemList[0]);  

In the example above, an array of 7 items is declared. The first item in the array (with value 1) is written to the screen. Individual array items can be accessed with 0-based index numbers between [ and ]. So [0] returns the 1st item, [1] the 2nd, and so on.



Flow Control

JavaScript "if" statements can be used to conditionally execute code:

var Age = SSI_GetValue("Q1");  
 
if(Age < 18)  
{  
alert("You do not qualify for this survey.");  
}  
 
In the code above, the value entered for Q1 is assigned to Age. If Age is less than 18 a message box appears.

If there are multiple paths that can be taken the "else if" statement can be used. For example:

var Age = SSI_GetValue("Q1");  
 
if(Age < 18)  
{  
alert("You do not qualify for this survey.");  
}  
else if(Age < 65)  
{  
alert("You qualify for group 1.");  
}  
else if(Age >= 65 && Age <= 125)  
{  
alert("You qualify for group 2.");  
}  
else  
{  
alert("Are you sure you are older than 125?");  
}  

If the first "if" statement is false, the next "else if" logic is tested, and so on. If a section evaluates to true, its code is executed. Execution flow then continues after the final "else" or end of the block.

The following symbols are used in conditional logic:
·"&&" for AND  
·"||" for OR  
·"==" for equal  
·<, >, <=, >=, etc.  

The "for loop" allows your code to loop for a given amount of iterations. For example:

var myArray = [1,2,3,4,5];  
var i = 0;  
var sum = 0;  
 
for(i = 0; i < myArray.length; i++)  
{  
sum += myArray[i];  
}  
 
alert(sum);  

The variable "i" starts at 0 and counts up to the length of the array (in this case 5). The code inside the "for" loop block is executed 5 times. The code accesses each item in the array, storing the sum of all the items in the "sum" variable.



Functions

Functions are sections of code that can be defined and used when needed by "calling" them. For example:

function AddTwo (Num1, Num2)  
{  
var Result = Num1 + Num2;  
 
return Result;  
}  
 
alert(AddTwo(4, 6)); //The value 10 will appear in a pop-up box.  
alert(AddTwo(56, 33); //The value 89 will appear in a pop-up box.  

In the code above, a function named "AddTwo" is defined. This function takes two numbers for input named "Num1" and "Num2". Any two numbers that are passed into this function are added and the result is returned.

Functions are best defined in the HTML <head> Tag (Survey Settings, Headers and Footers) or in a separate file that is included in the HTML <head> Tag. This makes it so that the functions are available throughout the whole study.



Form Objects

Each survey page created by SSI Web contains an HTML form tag named "mainform". All of the HTML input elements for the questions on this page are inside this form. Using JavaScript, you can get access to JavaScript objects that represent these form elements. Having access to these form elements gives you access to their properties and functions. The following JavaScript code assigns a form object to a variable:

var Q1Obj = document.mainform["Q1"];  

This can also be done by calling an SSI Web JavaScript system function like this:

var Q1Obj = SSI_GetFromObject("Q1");  

Now Q1Obj can be used to get and set values and to set up events etc. For example:

Q1Obj.value = 5;  
Q1Obj.addEvent("keyup", SetToFive);  
 
function SetToFive()  
{  
this.value = 5;  
}  

Here, we are assigning a 5 to the "Q1" numeric question. This causes a 5 to appear in the numeric box on the screen. The next line of JavaScript then assigns an event to the question. If the respondent types into the Q1 box every time a key is pressed and released ("keyup") then the function "SetToFive" is called. In this function "this" represents "Q1Obj". This code essentially makes it so that the respondent cannot alter the value for "Q1". The events "keyup", "click", "mouseover", "mouseout", etc. can be used.

To get a value from a question on the page, use SSI_GetValue("QuestionName"). This function handles the complexities of different question types (radio, checkbox, numeric, etc.).



Custom JavaScript Verification

Warning:
This is an advanced area, intended for those who know JavaScript. You must completely test your survey and custom JavaScript code to ensure that it functions properly and that the data for your entire survey are being saved correctly. Sawtooth Software does not support your custom JavaScript.

There might be times when our default question verification will not accomplish the functionality you want. Most questions (with the exception of the password, Terminate/Link, and conjoint questions) have a Custom JavaScript Verification section. This is available by editing the question, clicking on the "Advanced" button, and then selecting the "Custom JavaScript Verification" tab.

Custom JavaScript Verification allows you to specify custom verification for your questions. Your custom verification, written in JavaScript, is invoked when the respondent clicks the "Submit" button. You can configure your custom JavaScript to be called "before" or "after" the built in question JavaScript verification.

Your respondents must have JavaScript enabled (most do) in order for your custom JavaScript to work.

custom_javascript

In the example above, an error message is displayed and respondents cannot continue the survey if they have specified that they are older than their father.

The age of the respondent ("respondentAge") and of the father ("fatherAge") are asked on the current page. These values have not been submitted to the server yet or recorded in the data file. They are on the same page where this custom JavaScript is executed. The values of questions on the same page as the JavaScript that you are writing are available through the following JavaScript:

SSI_GetValue("QuestionName")  

The JavaScript SSI_GetValue is defined in SSI Web's system JavaScript file ssi_javascriptX_X_X.js located in the graphics/system directory.

In the example above if the value of "respondentAge" is greater than or equal to "fatherAge" then "strErrorMessage" is set to a custom error message. Setting strErrorMessage equal to something other than empty will cause the system JavaScript to display an error message on the screen and highlight the current question. The current page will also not submit to the server as long as strErrorMessage has a value assigned to it.

If multiple questions on a single page all have custom JavaScript verification, then each section of custom JavaScript is run in order from top to bottom.

If you would like to retrieve information from previous pages you need to use SSI Script
. If the respondent's age was submitted on a previous page, the JavaScript would then employ SSI Script and look like this:

if([%respondentAge%] >= SSI_GetValue("fatherAge"))  

SSI Script executes on the server and the respondent's age (lets assume it is 37) is inserted. The resulting JavaScript is sent down to the browser and looks like this:

if(37 >= SSI_GetValue("fatherAge"))  




SSI Web JavaScript Library

SSI Web comes with a system JavaScript file named ssi_javascriptX_X_X.js. It is located in the graphics/system directory and is included and available on every page of the survey. The system JavaScript file is used by SSI Web to help validate responses to questions, fill in Constant Sum total boxes in real time, and to un-check select options when an "Other Specify" is chosen etc. There are a few functions from this library that you might find useful.

SSI_GetValue("QuestionName")
Returns the current value for the specified QuestionName, for any question type (radio, checkbox, numeric, etc.). A zero ("0") is returned for questions that have been left empty.  
 
Example:  
var Num1 = SSI_GetValue("Q1"); // returns the value of question Q1  
var FirstStateChecked = SSI_GetValue("State_1"); // If the first check box of question "State" is checked 1 will be returned, otherwise 0.  

SSI_GetFormObject("QuestionName")

Returns the object associated with the form element on the page for QuestionName.  
 
Example:  
var Num1Obj = SSI_GetFormObject("Q1"); // Assigns the form object for question "Q1" to "Num1Obj".  
Num1Obj.value = 46; // Assign the value of 46 to the Q1 question.  

SSI_RoundNumber(Number, NumDecimalPlaces)
Round "Number" to "NumDecimalPlaces".  

Example:  
var Value1 = SSI_RoundNumber(SSI_GetValue("Q1"), 2); // SSI_GetValue returns the value for Q1 it is then rounded to 2 decimal places.  
alert(Value1); // Assuming Q1 was 45.236 the Value1 would yield 45.24  
 
SSI_PriceFormat(Number, "ThousandSymbol", "DecimalSymbol")
Formats a number with the thousands symbol and decimal symbol.  
 
Example:  
var FormatValue = SSI_PriceFormat(5123693.25, ",", "."); // 5,123,693.25 is returned.  
 
SSI_CustomGraphicalCheckbox(GraphicalCheckboxObj, InputObj, blnCheck)

SSI_CustomGraphicalCheckbox is a function that has been provided so that you can write custom code that gets called when a graphical checkbox is clicked. This function must be defined by you in your custom JavaScript. The function will be called by SSI Web's system JavaScript each time a check box is clicked.  
 
GraphicalCheckboxObj represents the graphical item on the page that is being clicked. InputObj is the actual hidden checkbox on the page that the graphical checkbox represents. blnCheck is true if the checkbox has been checked, otherwise it is false.  
 
Example:  
function SSI_CustomGraphicalCheckbox(GraphicalCheckboxObj, InputObj, blnCheck)  
{  
if(InputObj.name == "mySelect_1" && blnCheck == true)  
{  
alert("The first box was checked");  
}  
}  

SSI_CustomGraphicalRadiobox(GraphicalRadioObj, InputObj)

SSI_CustomGraphicalRadiobox is a function that has been provided so that you can write custom code that gets called when a graphical radio button is clicked. This function must be defined by you in your custom JavaScript. The function will be called by SSI Web's system JavaScript each time a radio box is clicked.  
 
GraphicalRadioboxObj represents the graphical item on the page that is being clicked. InputObj is the actual hidden radio button on the page that the graphical radio button represents. When ever this function gets called the radio button represented by InputObj will have been checked.  
 
Example:  
function SSI_CustomGraphicalRadiobox(GraphicalRadioboxObj, InputObj)  
{  
if(InputObj.name == "mySelect")  
{  
alert("A radio button with the value " + InputObj.value + " has been selected.");  
}  
}  
 



JavaScript Debugging

You are responsible to ensure your custom JavaScript is working. The following tips are highly recommended when trying to debug your custom JavaScript:

Turn on script error reporting. This is done in Internet Explorer by clicking Tools | Internet Options | Advanced. Under the Advanced tab go to the Browsing section and check Display a notification about every script error. This is extremely useful in alerting you to mistakes in your code.  
 
Use the "alert( )" function. If you are unsure what certain values are at certain points in your code, you can print them out to the screen by using the "alert( )" function. For example:  
 
alert("My value at this point is: " + SSI_GetValue("Q1"));  
 
Firefox has a plug-in named "Firebug" that provides a powerful JavaScript debugger.  
 
Test your custom JavaScript in multiple browsers (e.g. Microsoft Internet Explorer, Firefox, etc.).