About this Resource
[Skip navigation][Access key info]SEARCH | SITE MAP
SELF-STUDY INDEX
Exploring online research methods - Incorporating TRI-ORM

Introduction to JavaScript

[Skip instructions]

[i] Click on the headings to open them. They will open on this page. Open the following link for further information about these headings if required.

Your browser does not support these headings. To ensure that the contents remain accessible, they have been automatically opened so that all the information on the page is displayed.

However, to take advantage of the headings and to ensure that the layout and design of this site are displayed correctly, you are recommended to upgrade to a current version of one of the following standards compliant browsers:

Glossary links are included within this page. If a word appears as a link, clicking on this link will show the definition of the word in a 'pop-up window'. Select the following link for information about these glossary links if required.

  1. Select the links see the definitions in a pop-up window.
  2. NB. If you use pop-up window blocking software, you will need to deactivate it for pop-ups on this site to use the glossary links. Alternatively, all glossary definitions can be seen on the 'Glossary' page in the 'Resources' section.
  3. Use of the glossary links is JavaScript dependent. If JavaScript is disabled, it will be necessary to open the 'Glossary' page to view the definitions. Opening this page in a new window may allow you to refer more easily to the definitions while you navigate the site.

Open/close headingIntroduction

The use of JavaScript (or other scripting languages such as VB Script) can add a number of enhancements to an online questionnaire. These include:

  1. Checking whether or not all questions have been answered correctly and prompting participants accordingly.
  2. Playing a part in effective questionnaire design, for example, by allowing instructions to be delivered when needed in pop-up windows or alert boxes and allowing the use of browser detection to test which browser a user has and whether or not he or she has certain technology installed.
  3. Improving the delivery of questions, for example by allowing data to be passed from page to page rather than being delivered on one long document, or by allowing randomisation.
  4. Allowing the collection of data such as date and time of submission, and information about the computer used by the participant such as the IP address or the browser

The pages which follow this one provide an outline of some of these uses of JavaScript and offer a number of scripts which can be used or adapted. Beyond this website, there are also a number of sites offering freely-available scripts for direct use or adaptation. In order to take advantage of these resources, an understanding of the basics of JavaScript is generally required.

This section will introduce you to the basic concepts by examining two simple HTML documents with JavaScript functionalities. JavaScript will be the scripting language used throughout, though the procedures and scripts will be similar for other languages.

 

Close heading CLOSE

Open/close headingAccessibility

It is important to bear in mind that JavaScript may reduce the accessibility of the questionnaire. Users of text-only or screen-reading browsers are likely to be unable to access any functionality provided by JavaScript, and it is also possible that JavaScript may not be fully supported in the user's browser or that he or she may have chosen to deactivate it.

Thus, while it can be used to enhance the functionality of the questionnaire, it is not good practice to produce a questionnaire that is not usable without JavaScript. Where any key functions are reliant on JavaScript (e.g. where the navigation and question delivery is controlled by JavaScript) it is important to inform the user of this and to offer alternatives.

The <noscript></noscript> tags can be used to deliver a message to users who are using a browser that does not support JavaScript. Anything placed between the tags will be displayed in cases where JavaScript is not available.

e.g.

<noscript>This questionnaire requires the use of JavaScript to function properly and it is not available in your browser. If you have disabled JavaScript in your browser settings, please enable it and refresh this page. If your browser does not support JavaScript and you would still like to complete the questionnaire, please email me for an alternative version.</noscript>

By placing a the following meta tag in the head of the document between <script></noscript> tags, it is also possible to redirect the user to a new document. In this case the redirect occurs immediately (0 seconds) and altpage.htm is the name of the document the user is redirected to (which is held in the same folder as the original page). In this way, for example, users without JavaScript can be taken to a version of the questionnaire that does not require it, or to further instructions and contact details.

<meta http-equiv="refresh" content="0;url=/altpage.htm">

It should be noted, however, that automatic page refreshing may also affect the accessibility of the questionnaire to some users, and thus that displaying a message with a link may be a better way of redirecting users. If the user has a browser which does not allow redirects, it will also be necessary to add a link within the <script></noscript> tags to allow the user to navigate to the page manually.

For accessibility, it is also important that JavaScript actions are not dependent on mouse actions such as dragging or double clicking. Where this the case, keyboard-accessible alternatives should also be provided. See 'Event handlers' section below.

 

Close heading CLOSE

Open/close headingExample 1: A welcome message

The following example takes the contents of a text box and inserts it into an alert box when the user clicks on the button.

[?] Complete the text box and submit your answer (it will be dealt with client side and will not be sent away from your computer).

What is your name?

If this were the entire page, the HTML and JavaScript would be as follows:

<html>
<head>
<title>Hello</title>
<link href="mainstyle.css" rel="stylesheet" type="text/css">
<script language="javascript" type="text/javascript">
function showAlert() {
alert("Hello " + document.egForm1.namebox.value + ".");
}
</script>
</head>
<body>
<div class="ques">
<form name="egForm1" action="" method="post">
<p>What is your name?</p>
<p><input type="text" name="namebox" />
<input type="button" name="submit1" value="Submit" onclick="showAlert();">
<input type="reset" name="reset1" value="Reset" /></p>
</form></div>
</body>
</html>

The majority of the document is HTML with some JavaScript added. Before considering the JavaScript, check your understanding of the HTML sections and, if necessary, read the brief explanation that follows.

Open/close headingExplanation

The HTML document has a head section that includes a title and a link to a Cascading Style Sheet to add design features (See the 'Introduction to CSS called "mainstyle.css". The body contains a form which is styled using <div class></div> tags. These apply a style called "ques" which is defined in the Style Sheet to everything between the tags. The form contains three input elements - a text box called "namebox", a button called "submit" with "Submit" as the text (the value), and a reset button called "reset" with "Reset" as the value.

 

Close heading CLOSE

 

Close heading CLOSE

Open/close headingJavaScript within the HTML document structure

[i] You can select the following link to open the document in a new window to make it easier to see the different sections in the context of the whole.

The main script is placed in the head of the document, between script tags as follows:

<script language="javascript" type="text/javascript">

and

</script>

It could also have been saved in a separate text file with the extension '.js'. This would be linked to the web page through a link placed in the head:

<script language="javascript" src="filename.js" type="text/javascript"></script>

 

Close heading CLOSE

Open/close headingFunctions

The action of the script takes place within a function called showAlert which is surrounded by curly brackets ({}).

function showAlert() {
alert("Hello " + document.egForm1.namebox.value + ".");
}

In this case, an alert box is shown with the contents of the text box incorporated into a message. The function can be explained as follows:

The value of the box is extracted and placed between two strings (text variables), namely "Hello " and "." (The quotation marks identify them as strings). The alert function is then triggered which places everything within the brackets in an alert box. The semi-colon (;) is placed at the end of each line of the function.

As in this example, a function is a block of code that carries out a particular action. In effect the code is not carried out until the function is 'called' from within the document when a particular event occurs (such as the user clicking a submit button).

The basic structure of a function is as follows:

functionName(){

Add function here...

}

The brackets following the function name allow different arguments to be included when it is called by different elements.

In the case of the example, this is not done - the code will always display the same message and the contents of the same text box when the function is called. However, the inclusion of arguments allows functions to be created which can be reused at different times by different elements in the document. In this case, a message and a reference to a particular text box name could be added when the function is called to allow it to display different messages along with the contents of different boxes.

They can thus be a very efficient way of carrying out different actions with one block of code (see 'Using arguments within functions' below).

 

Close heading CLOSE

Open/close headingEvent handlers

This function is 'called' by the onclick code placed in the button tag:

<input type="button" name="submit" value="Submit" onclick="showAlert();">

The onclick code is an example of an 'event handler' which triggers an action when a particular event occurs. In this case, the showAlert() function happens when the participant clicks on the button. Other examples of important event handlers are:

Event handler Description
ondblclick
Placed in the tag of a button or link, the action happens when the user uses the mouse to double select the object.

onmouseover / onmouseout
The action happens when the user places the mouse over a button or link / removes the mouse from the button or link.
onfocus / onblur
Usually placed in the tag of a form control, the action happens when the element receives focus (the user selects it) / loses focus (the user moves away).

Onchange The action happens when a control loses focus (the user clicks away) and the value has been changed.

Onsubmit/onreset Placed in the form tag, the action happens when a form is submitted (the user presses the 'submit' button) / reset (the user presses the reset button).

Onload / onunload Placed in the body tag of a document, the action occurs when the page loads / unloads.

To ensure the accessibility of a questionnaire, any event handler that is dependent on the use of a mouse should be avoided. This will allow the JavaScript function to be activated by those using a keyboard or equivalent such as a voice activated browser. Where event handlers such as onmouseover or onmouseout are used, they should also be combined with onfocus or onblur events which will trigger the action when a user tabs to a button or similar element. For example in the following 'image flip' code, a function to change an image is called by the onmouseover event handler. The onmouseout handler calls a second function to change the image back. Adding the onfocus="this.onmouseover();" and the onblur="this.onmouseout();" code ensures that the same actions will take place when a user without a mouse tabs to or away from the image.

<img src="picture.gif" alt="picture 1 " name="i1" width="20" height="20" onmouseover="swapOn();" onmouseout="swapOff();" onfocus="this.onmouseover();" onblur="this.onmouseout();" />

 

Close heading CLOSE

Open/close headingAccessing data in controls

Elements in a web page are referenced by JavaScript using the 'tree-structure' of the document to refer to a particular element by name.

The contents of the text box in the example are referenced using the following:

document.egForm1.namebox.value

This refers to the value (the text) of the text box called namebox within the form called egForm1 within the document.

By giving all the form controls on a page a unique name, it is possible to use this type of referencing to extract or set their value.

As an alternative to writing out the full reference where there are numerous references to controls within a form, it is also possible to make use of the 'this' which is used in JavaScript to allow an object to refer to itself.

If an event handler is in the form tag, 'this' can therefore replace the words 'document.egForm1' in the reference.

If it is in a button within the form, the syntax 'this.form' can be used to refer to the form (i.e. the form that contains this).

To refer to a text box control called 'box1' from the button within the form, 'this.form.box1' can be used instead of 'document.egForm1.box1'. (i.e. box1 which is in the form that contains this).

This referencing is illustrated by the following example which is a form called frm1 containing two text boxes called box1 and box2, and a button called btn1. Code is added to the onclick event handler of the button which will display the contents of box1 in box2 when the user presses the button, as follows:

Box 1 Box2

The code is:

<p> Box 1 <input type="text" name="box1" />
<input type="button" name="btn1" value="Go" onclick="document.frm1.box2.value=document.frm1.box1.value;" /> Box2 <input type="text" name="box2" /></p>

There is no difference if the full reference is replaced with the shortened version using 'this', as follows:

onclick="this.form.box2.value = this.form.box1.value";>

Although it is not a great deal shorter, using this syntax can make code more flexible and can avoid errors where the form name is referenced incorrectly (the this.form syntax automatically feeds in the correct name). If it is used with arguments, it can make it easier to reuse functions with different forms and controls. (see section below)

 

Close heading CLOSE

Open/close headingUsing arguments with functions

The use of arguments can be illustrated by the alert function which is used to display the name from the text box in example 1.

It is possible to create one function with an argument (given the name 'msg') that will be the message displayed when the function is called, as follows:

function showMessage(msg) {

alert(msg + ".");

}

A string can be added to an onclick event handler which is then fed into the function when the function is called. This means that a different message can be displayed each time and it is not necessary to write a new function for each message.

e.g. All the buttons and links in the following paragraph use this same function to display a different message:


The following link is to message 2. It is an example of how a link can trigger an event in the same way as a button, using an 'empty' link to the JavaScript function as follows: <a href="JavaScript:void(0);">.

The code in the HTML document which calls the function is as follows:

<p><input type="button" name="btn2" value="Message 1" onclick="showMessage('This is message 1');" /><br />
The following link is to <a href="JavaScript:void(0);" onclick="showMessage('This is message 2');">message
2.</a> It is an example of how a link can trigger an event in
the same way as a button, using an 'empty' link to the JavaScript function as follows: <strong><a href="JavaScript:void(0);"></strong>. <br />
<input type="button" name="btn3" value="Message 3" onclick="showMessage('This is message 3');" />

If the same concept is applied to example 1 (which displayed a welcome message incorporating the user's name taken from a text box), it is possible to feed in the text box name as a second argument. The name is then passed to the function along with the message, allowing it to be reused within or between documents.

The original function is:

function showAlert() {
alert("Hello " + document.egForm1.namebox.value + ".");
}

It is altered by adding argument names between the brackets, and replacing the message and text box reference with these name as follows

function showAlert(msg, box) {
alert(msg + " " + box.value + ".");
}

This tells the function to expect the relevant information to be fed in when the function is called.

e.g.

<input type="button" name="submit1" value="Submit" onclick="showAlert('Hello there', this.form.box1);">

The first argument is a string which is fed into the function as msg. It is placed within single quotation marks rather than double as double quotation marks would interfere with the tag. A comma then follows to separate the arguments.

The second argument uses the 'this' shorthand to tell the function to take and display the contents from the text box called 'box1' within the same form as the button that was clicked (this.form).

It can thus be called from different boxes in the document and deliver a different message accordingly:

What is your name?

What is your full name?

The code in the HTML document is as follows:

<form name="egForm2" action="" method="post">
<div class="ques">
<p>What is your name?</p>
<p><input type="text" name="box1" />
<input type="button" name="Submit" value="Submit" onclick="showAlert('Hello there', this.form.box1);"></p>
<p>What is your full name?</p>
<p><input type="reset" name="reset" value="Reset" />/>

<input type="text" name="box2" />
<input type="button" name="Submit2" value="Submit" onclick="showAlert('or perhaps I should call you', this.form.box2);">
<input type="reset" name="reset2" value="Reset" /></p>
</div>
</form>

By placing the script in a file linked to a number of documents, it can also be used across an entire site.

Although this is not very useful for a welcome message script, applying the use of arguments and reusable functions to common tasks such as form validation can be a very efficient way of carrying them out.

 

Close heading CLOSE

Open/close headingExample 2: Simple validation

This example checks that a value has been entered in the text box, preventing submission until this is the case. If a value has been entered a welcome message is displayed.

What is your name?

If this were the entire page, the HTML and JavaScript would be as follows:

<html>
<head>
<link href="../generic/main.css" rel="stylesheet" type="text/css">
<title>Simple validation</title>

<script language="javascript" type="text/javascript">

function validateForm(form) {
if (form.namebox.value ==""){

alert("please enter your name.");
form.namebox.focus();
return false;
}

else {

alert("Welcome " + form.namebox.value + ".");
return true;
}

}

</script>

</head>
<body>
<div class="ques">
<form name="egForm2" action="" method="post" onSubmit=" return validateForm(this);">
<p>What is your name?</p>
<p> <input type="text" name="namebox" />
<input type="submit" name="submit" value="Submit" />
<input type="reset" name="reset" value="Reset" /></p>
</form></div>
</body>
</html>

 

[i] You can select the following link to open the document in a new window to make it easier to see the different sections in the context of the whole.

 

The HTML sections of the document are almost the same as those in example 1. Again, there is a head section that includes a title and a link to a Cascading Style Sheet called "mainstyle.css". The body contains a form which is styled using <div class></div> tags. These apply a style called "ques" which is defined in the Style Sheet to everything between the tags. The form contains three input elements - a text box called "namebox", a button called "submit" with "Submit" as the text (the value), and a reset button called "reset" with "Reset" as the value.

The function that carries out the action is called validateForm(). It is placed between <script></script> tags and is called by the onSubmit event handler when the participant submits the form. The onSubmit handler is specifically designed for form validation. It is followed by the key word return which means that the results of the validateForm() function will be returned to the piece of code. These results must be either 'true' (the submission proceeds.), or 'false' (the submission is blocked).

The onSubmit handler includes an argument which is the reference to the form (this). This feeds the full reference to the form name (document.egForm2) into the function when it is triggered. The function then checks whether the box is empty, and displays an alert message accordingly. It also returns the required 'true' or 'false' value that will allow or block the submit action. Details about the conditional section of the function (if/else) are given below.

 

Close heading CLOSE

Open/close headingConditionals

Conditionals are integral to validation and, indeed, to programming of all kinds. They allow the code to test whether or not certain conditions have been met and to perform different actions accordingly.

The basic structure of conditionals in JavaScript is as follows:

if(Condition A){

Perform an action;

}

else if(condition B){

Perform an alternative action;

}

else {

Perform an alternative action in any other situation;

}

Like functions, the actions that take place if a condition is met are placed within curly brackets '{}'.

The conditions that the code tests for are placed within brackets '()'.

The function in the example 'validateForm()' basically consists of a conditional to test whether the text box is empty.

if (form.namebox.value =="")

The '==' symbol is an operator meaning 'is equal to', so the conditional tests whether the value is equal to an empty string ( "").

If this is the case, the following three actions are carried out:

{
alert("please enter your name.");
form.namebox.focus();
return false;
}

  1. An alert box delivers a 'please enter your name' message.
  2. The text box is given the focus through the 'focus()' method (i.e. the curser is placed inside the text box ready for it to be filled in).
  3. 'False' is returned to the onSubmit attribute in the form tag preventing the form submission from proceeding.

If it is not the case, the action is not carried out and the code moves on to the 'else' statement which performs the following actions if the value is equal to anything else except for an empty string(""):

else {
alert("Welcome " + form.namebox.value + ".");
return true;
}

  1. An alert box delivers a welcome message consisting of 'Welcome ' and the contents of the text box.
  2. 'True' is returned to the onSubmit attribute in the form tag allowing the form submission to proceed.

The else statement does not test for specific conditions, but provides a means of carrying out an action if any other condition is met but those specified.

In this case, it could be replaced with an 'else if' statement to test whether the box is not empty:

else if (form.namebox.value !="")

The '!=' symbol is an operator meaning 'is not equal to', so the conditional tests whether the value is not equal to an empty string ( ""). Other common operators used in conditionals are as follows:

Operator Meaning
x > y
x is greater than y
x < y
x is less than y
x >= y
x is greater than or equal to y
x <= y
x is less than or equal to y

Multiple conditions can also be tested for using the following operators:

Operator Meaning
condition 1 && condition 2
condition 1 and condition 2
condition 1 || condition 2
condition 1 or condition 2

Thus the following conditional would display an alert box message and prevent submission of the form if a text box called 'agebox' for a question about age is left blank or does not contain a number.

if (form.agebox.value =="" || isNaN(form.agebox.value) == true){

alert("Please enter your age as a number.");
return false;

}

isNaN(), tests to see whether a value in the brackets is Not a Number. The condition will be true if letters or any other characters are contained in the box.

 

Close heading CLOSE

Open/close headingLearning activity: Review

[?] The HTML and JavaScript from the 'simple validation' example is shown in the text box below. Amend the contents to make the changes outlined below.

You can use the 'view page' link to open the text box contents as a new HTML document. When you are have finished, select the 'suggested answer' link to compare your HTML and JavaScript with a model.

Changes

  1. Change the question to 'What is your age?' and replace the textbox called namebox with one called agebox. Set the width and the maximum number of characters to 3 characters using the size and maxlength attributes. Change any references to the name in the script.
  2. Rewrite the validateForm() function as follows:
    1. If the user attempts to submit the form with either a non-numerical value in the text box or a blank text box, deliver an alertbox with the message 'Please enter your age as a number'. Give focus to the box and set its value to an empty string (""). Return false to the event handler.
    2. If the user submits the form with a value less than 18, deliver the message 'You must be 18 or over to complete this questionnaire', and return false to the event handler.
    3. In other cases, deliver the message 'Welcome to this questionnaire', close the window using the close() method and return true to the event handler.

View Page | Reset text box | Suggested answer

[i] The links will open in a new window, which you should close to return to this page.

 

Close heading CLOSE

  © 2004-2010  All rights reserved    |    Maintained by ReStore    |    About this website    |    Disclaimer    |    Copyright    |    Citation policy    |    Contact us