Category Archives: JavaScript

JavaScript quiz tutorial

This tutorial explains how to create a quiz program in the JavaScript language which will look like this (you can change the theme):

quiz

The quiz will look like this when the user has finished it:

quiz_complete

By following this tutorial you will develop the following programming skills:

Please follow the steps below. You can download the complete code at the bottom of this page, but make sure you read the steps so you know what each part of the code is responsible for.

Setting up the HTML code

To begin, create a new html file eg. quiz.html in a coding text editor. You need to add some HTML code in the body section of an html file which will create a heading (in this example it is a h2 size heading) with an id of ‘test_status‘ and a div with an id of ‘test‘. The test_status heading will display the status of the quiz eg. “Question 2 of 4”, or “Test completed”. The ‘test’ div will display the actual questions and possible answers in the quiz. Use the code below to get started.

<html lang="en">
<head>
<meta charset="utf-8"/>
<title>Quiz</title>

</head>
<body>
<h2 id="test_status"></h2>
<div id="test"></div>
</body>

</html>

Now that you have a heading a a div in your HTML code, it is time to apply a style to them by adding some CSS code. In the head section of the HTML file, under the title tags, add the following code:

<style>
div#test{ border:#5AB029 3px solid; padding:10px 40px 40px 40px; background-color:#E5FCE3; width:50%;}
</style>

You can change the code above by changing the border or background colours, border thickness and padding, or adding extra style properties.

Setting up the JavaScript code

Inside the head section of the HTML code under your </style> tag, add the following code:

<script type="text/javascript">
var pos = 0;
var correct = 0;
var test, test_status, question, choice, choices, chA, chB, chC;
</script>

The code above will create several variables. Firstly, the pos variable is used to record what the position the user is at in the test eg. question 3 out of 4. The correct variable stores the number of questions answered correctly. The test variable contains the ‘test’ div and the test_status variable is used to contain the ‘test_status’ heading which displays the user’s progress in the test.

The question variable will contain a question grabbed from an array, the choice variable will contain the user’s selected answer for a question, choices variable will contain the possible answers that will be displayed to the user, and chA, chB, and chC variables will contain each possible answer (A, B, or C) in the multiple choice quiz.

Adding the questions, possible answers, and answer key to the quiz

Now the questions need to be created along with their possible answers and the correct answer (answer key). In this example, we will have four questions (you can add more) with three multiple choice options for each question (A, B or C). To do this, we make a multidimensional array which contains the questions, the options for each question, and the answer key for each question. Add the code below and change the questions to your liking.

This code goes inside the script tags under the variables you created in the previous step.

var questions = [
  ["What is 36 + 42", "64", "78", "76", "B"],
  ["What is 7 x 4?", "21", "27", "28", "C"],
  ["What is 16 / 4?", "4", "6", "3", "A"],
  ["What is 8 x 12?", "88", "112", "96", "C"]
  ];

Create the get function

This quiz needs to get elements from the web page (the heading and the div) and then modify those elements several times. Rather than constantly typing the document.getElementById(); method over and over again, we can simply turn it into a function called get. Add this code inside the script tags after the array you made in the previous step.

function get(x){
  return document.getElementById(x);
}

Create the renderQuestion function

The renderQuestion function will be used to get the ‘test‘ div, check the user’s position in the quiz, and if they have not yet completed the quiz then they will be served different questions. The function will display the user’s progress and the actual question and options to the user. The user must choose an answer by selecting a radio button next to an answer and then click the ‘Submit Answer’ button.

Add this code inside the script tags below the get function you created in the previous step.

function renderQuestion(){
  test = get("test");
  if(pos >= questions.length){
    test.innerHTML = "<h2>You got "+correct+" of "+questions.length+" questions correct</h2>";
    get("test_status").innerHTML = "Test completed";
    // resets the variable to allow users to restart the test
    pos = 0;
    correct = 0;
    // stops rest of renderQuestion function running when test is completed
    return false;
  }
  get("test_status").innerHTML = "Question "+(pos+1)+" of "+questions.length;
  question = questions[pos][0];
  chA = questions[pos][1];
  chB = questions[pos][2];
  chC = questions[pos][3];
  test.innerHTML = "<h3>"+question+"</h3>";
  // the += appends to the data we started on the line above
  test.innerHTML += "<input type='radio' name='choices' value='A'> "+chA+"<br>";
  test.innerHTML += "<input type='radio' name='choices' value='B'> "+chB+"<br>";
  test.innerHTML += "<input type='radio' name='choices' value='C'> "+chC+"<br><br>";
  test.innerHTML += "<button onclick='checkAnswer()'>Submit Answer</button>";
}

Create the checkAnswer function

The checkAnswer function is used to, you guessed it…check the answer. While the quiz is incomplete, each user choice will be checked and compared with the correct answer associated with each question (stored in the questions array). At the end of this question being called, the renderQuestion will be called.

Add the code below inside your script tags under the renderQuestion function you created in the previous step.

function checkAnswer(){
  // use getElementsByName because we have an array which it will loop through
  choices = document.getElementsByName("choices");
  for(var i=0; i<choices.length; i++){
    if(choices[i].checked){
      choice = choices[i].value;
    }
  }
  // checks if answer matches the correct choice
  if(choice == questions[pos][4]){
    //each time there is a correct answer this value increases
    correct++;
  }
  // changes position of which character user is on
  pos++;
  // then the renderQuestion function runs again to go to next question
  renderQuestion();
}

Get the quiz to load

The last step involves adding one line of code that will run the renderQuestion function as soon as the page has loaded (using an event listener that checks for a load event). When that function is loaded, the questions will be presented to the user and the quiz will begin.

Add the code below inside your script tags in your code. Add it below the checkAnswer function you created in the previous step. make sure you have ended the script section by closing it with the </script> tag!

window.addEventListener("load", renderQuestion, false);

And that’s it! You have now created a JavaScript quiz game. Challenge yourself by trying to add the following features to your quiz:

  • Add more questions (easy!)
  • Change the quiz theme (background colours/gradient, border, font style, etc)
  • Tell the user which questions they answered incorrectly
  • Display a visual progress bar during the test
  • Display the user’s score as a percentage value
  • Allow the user to re-take the quiz
  • Add more possible answers (eg. A, B, C, D)
  • Store the results in a database using PHP/MySQL (tricky)

Complete code

Here is the complete JavaScript code for the quiz program:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<title>Quiz</title>

<style>
div#test{ border:#5AB029 3px solid; padding:10px 40px 40px 40px; background-color:#E5FCE3; width:50%;}
</style>

<script type="text/javascript">
// pos is position of where the user in the test or which question they're up to
var pos = 0, test, test_status, question, choice, choices, chA, chB, chC, correct = 0;
// this is a multidimensional array with 4 inner array elements with 5 elements inside them
// if you don't want answers viewable in the code, then you should use PHP and mySQL database
var questions = [
  ["What is 36 + 42", "64", "78", "76", "B"],
  ["What is 7 x 4?", "21", "27", "28", "C"],
  ["What is 16 / 4?", "4", "6", "3", "A"],
  ["What is 8 x 12?", "88", "112", "96", "C"]
  ];
// this get function is short for the getElementById function	
function get(x){
  return document.getElementById(x);
}
function renderQuestion(){
  test = get("test");
  if(pos >= questions.length){
    test.innerHTML = "<h2>You got "+correct+" of "+questions.length+" questions correct</h2>";
    get("test_status").innerHTML = "Test completed";
    // resets the variable to allow users to restart the test
    pos = 0;
    correct = 0;
    // stops rest of renderQuestion function running when test is completed
    return false;
  }
  get("test_status").innerHTML = "Question "+(pos+1)+" of "+questions.length;
  question = questions[pos][0];
  chA = questions[pos][1];
  chB = questions[pos][2];
  chC = questions[pos][3];
  test.innerHTML = "<h3>"+question+"</h3>";
  // the += appends to the data we started on the line above
  test.innerHTML += "<input type='radio' name='choices' value='A'> "+chA+"<br>";
  test.innerHTML += "<input type='radio' name='choices' value='B'> "+chB+"<br>";
  test.innerHTML += "<input type='radio' name='choices' value='C'> "+chC+"<br><br>";
  test.innerHTML += "<button onclick='checkAnswer()'>Submit Answer</button>";
}
function checkAnswer(){
  // use getElementsByName because we have an array which it will loop through
  choices = document.getElementsByName("choices");
  for(var i=0; i<choices.length; i++){
    if(choices[i].checked){
      choice = choices[i].value;
    }
  }
  // checks if answer matches the correct choice
  if(choice == questions[pos][4]){
    //each time there is a correct answer this value increases
    correct++;
  }
  // changes position of which character user is on
  pos++;
  // then the renderQuestion function runs again to go to next question
  renderQuestion();
}
window.addEventListener("load", renderQuestion, false);
</script>
</head>
<body>
<h2 id="test_status"></h2>
<div id="test"></div>
</body>

</html>

Introduction to JSON

JSON stands for JavaScript Object Notation. JSON is a light-weight data interchange format that uses JavaScript syntax in text format that can be read and used as data by other programming languages.

In this example, we will use JSON to define an object with an array of records – we will use the Avengers characters for this example. Watch the video below and then scroll down to see the sample code.

Here is the sample code:

<!DOCTYPE html>
<html>
<head>
 <title>JSON</title>
</head>
 
<body>
<h2>The Avengers</h2>
 
<p id="avengerstext"></p>
 
<script>
var text='{"avengers":['+
'{"firstName":"Bruce","lastName":"Banner"},'+
'{"firstName":"Tony","lastName":"Stark"},'+
'{"firstName":"Natalia","lastName":"Romanova"},'+
'{"firstName":"Thor","lastName":"Odinson"}]}';
 
obj = JSON.parse(text);
document.getElementById("avengerstext").innerHTML=obj.avengers[0].firstName+" "+obj.avengers[0].lastName+"<br>"+obj.avengers[1].firstName+" "+obj.avengers[1].lastName+"<br>"+obj.avengers[2].firstName+" "+obj.avengers[2].lastName+"<br>"+obj.avengers[3].firstName+" "+obj.avengers[3].lastName;
 
</script>
 
</body>
</html>

Sample code: Using jQuery to push array elements into an HTML table

The sample code shows how to use jQuery to push the elements inside a 2D array into an HTML table. If you are not familiar with jQuery, click here to find out more about the jQuery library.

Note that the code below links to the jQuery 2.1.0 library which is hosted on the jQuery website. You can download this file and store it locally or upload it to your own site so that you don’t have to hot-link to the jQuery website.

Here is the code:

<!DOCTYPE html>
<html>
<head>
 <title>Putting JS array elements into a table using jQuery</title>
 
 <script type='text/javascript' src='//code.jquery.com/jquery-2.1.0.js'></script>
 <script type='text/javascript'>
 $(window).load(function(){
 var itemsArray = [];
 itemsArray[0] = ["a","b","c"];
 itemsArray[1] = ["d","e","f"];
 itemsArray[2] = ["g","h","i"];
 itemsArray[3] = ["j","k","l"];
 itemsArray[4] = ["m","n","o"];
 itemsArray[5] = ["p","q","r"];
 itemsArray[6] = ["s","t","u"];
 itemsArray[7] = ["v","w","x"];
 itemsArray[8] = ["y","z",];
 
 var table = $('#myTable');
 var row, cell;
 for(var i=0; i<itemsArray.length; i++){
 row = $( '<tr />' );
 table.append( row );
 for(var j=0; j<itemsArray[i].length; j++){
 cell = $('<td>'+itemsArray[i][j]+'</td>')
 row.append( cell );
 }
 }
 
 });
 
</script>
 
 
</head>
<body>
 <table id="myTable">
</table>
 
</body>
 
 
</html>

This will be the result of the code above:

Screen Shot 2015-03-21 at 11.31.11 am

Multidimensional arrays in JavaScript

This tutorial will explain how to create, access, and modify elements in a multidimensional array. In the example here, we will work with a 2D (two dimensional) array in JavaScript.

We already know that an array is a better way of storing several related values than creating multiple variables. But what if we want to store several characteristics for each element in an array? Well, we can use two dimensional arrays for that! Watch the video below to find out more and then scroll down to see the code.

In the example code below, we have a two dimensional array that stores several people in an the array. For each person, the array also stores characteristics about them including their name, age, and gender. In other words, there are elements inside elements in the array.

If we wanted to access the first element in an array we would usually use the code arrayname[0]. If we want to access the first element inside the first element of the array, we would access it using the code arrayname[0][0]. Basically, there are two dimensions in the array. We access the first element in the first dimension, and the first element from its second dimension.

Check out the code below to see how you can create a 2D array, access elements inside it, and modify values in the array.

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="utf-8"/>
 <title>JavaScript - Multidimensional Arrays</title>
 
 <script type="text/javascript">
 
 // This is 2 dimensional array which stores name, age, and gender for different people
 
 var people = [
 ["John", 16, "Male"],
 ["Mary", 42, "Female"],
 ["Jason", 21, "Male"]
 ];
 
 // Remember that array elements start counting from 0
 // To access the name of the first person in the array, we need to access people[0][0]
 document.write(people[0][0] + "<br/>");
 
 // This will access the age of the second person in the array:
 document.write(people[1][1] + "<br/>");
 
 // This will access the gender of the third person in the array:
 document.write(people[2][2] + "<br/>");
 
 // To change the age of the third person (Jason) in the array:
 people[2][1]=22;
 document.write(people[2][1] + "<br/>");
 
 // To add an extra person to the array:
 people[3]=["Sarah", 36, "Female"];
 
 // This will display all elements (name, age, gender) inside the fourth array element
 document.write(people[3]);
 
 </script>
 
</head>
<body>
 
</body>
</html>

The code above will produce output that looks like this:

Screen Shot 2015-03-20 at 10.22.59 pm


Next tutorial: 
If statements

Treating text input from a form as an integer or float

If you have completed the User Input with Forms tutorial, you will now know how to ask the user for text input through a form, and use that input in some way. However, if you trying collecting input from the user in the form of numbers and then try to do some logical operations on those numbers, you may run into problems.

The first problem is that any text input will be treated as a string, not an integer. So if you try to compare two numbers eg. check if the inputted number is equal to 5, JavaScript will be trying to check if a string input is equal to a number and will not be checking if an integer input is equal to a specific integer.

The video and sample code below shows an example of using parseInt() to treat text input from a textbox as an integer value. You can also use parseFloat() to parse a string as a float (real number with decimal places). The video also shows how to grab the value from a textbox by using document.getElementById(‘idname’).value so that a logical operation can happen

The example used in the video and the code below is a simple math question game. The program displays a math problem to the user. The user can enter their answer in a textbox and the page will display a message if the user gets the correct answer. Watch the video below to see how to write the code for this program.

Once you have completed the tutorial, your program should work like this:

MathGame

Here is the code for the program:

<html>
<head>
<title>Simple math game</title>
<script type="text/javascript">
var answer = 15; // this is the answer to the math question
var attempt; // the user's attempt will be stored in this variable
 
function guess(){
 attempt = document.getElementById('attempt').value;
 attempt = parseInt(attempt); // this will now treat the textbox input value as an integer
 var result = document.getElementById('result');
 
 if (attempt == answer){
 result.innerHTML = "Correct!";
 }
 else{
 result.innerHTML = "Try again.";
 }
 
}
 
</script>
</head>
<body>
 <p>What is the answer to 10+5?</p>
 <form>
 Enter your answer:<input type="text" id="attempt"/><br/>
 <input type="button" value="Submit" onclick="guess();"/>
 </form>
 <p id="result">Enter your answer in the textbox above. It must be a number only.</p>
 
 
</form>
</body>
</html>

 Next tutorial: Submitting forms

Keyboard events in JavaScript

In earlier JavaScript tutorials we looked at using onclick and onmouseover events to call a function when a user clicked or rolled their mouse over a button, and also the onload event to start an animation when a page had loaded. We can also use keyboard events such as when a key has been pressed on the keyboard.

Watch the video below which demonstrates how to use keyboard events, and then scroll down to see the sample code.

There are three different types of keyboard events we are using:

  • keydown
  • keypress
  • keyup

A keydown event is triggered when a button on the keyboard has been pressed down. A keyup event is triggered when a button that has been pressed on the keyboard is released. These events use keycodes to represent the many letters, numbers and other keys available. A keycode is returned to the program when a button has been pressed. You can find a list of keycodes here.

A keypress event is only triggered when you click on a key that represents a character such as a letter or number. A keypress event will tell the program what character the key represents, while the keydown and keyup events only tell the program what key has been pressed or released.

Keydown and keyup events will not tell the program if a letter key that was pressed is uppercase or lowercase. However, if you use the keypress event, then a program could detect when the Shift button and a character key were pressed to make an uppercase letter or another character (eg. Shift + p = P key, and Shift + 5 = % key).

The keydown and keyup events only trigger once when a key is pressed. Another thing to note is that keycodes return a number which represents a key pressed, and they work with keydown and keyup events, while ASCII codes return an ASCII code and work with keypress events. This link shows both the keycodes and ASCII codes that represent different keys.

The code below shows how to use a keydown event and a keycode of 65 to detect when the ‘a’ letter key is pressed on the keyboard. If the ‘a’ key is pressed, then an alert message is displayed.

<html>
 
<head>
<title>Key press events</title>
<script>
 
window.addEventListener("keydown", checkKeyPress, false);
// The parameters of the event listener are event, function to run, useCapture (optional).
// This event listener runs checkKeyPress function when a key is pressed down
// You can use keydown or keyup to check what key has been pressed or released
 
 
// this function checks to see if the letter 'a' key has been pressed
function checkKeyPress(key) {
 if (key.keyCode == "65") {
 alert("The 'a' letter key has been pressed.");
 // 65 is the keycode that is returned when the 'a' letter key is pressed
 // if you use keypress event instead of keydown/up then you must use ASCII code instead of keycode
 }
}
 
</script>
</head>
 
<body>
 <p>Press the 'a' key to see the alert message<p>
</body>
 
</html>

Try it yourself

Try the above code and then use the keyup event instead to see what happens. Change the keycode in the ‘if’ statement to test other key presses, and then try using the keypress event with ASCII codes. Also try using canvas.addEventListener in a canvas instead of window.AddEventListener.

Hints

As an example, the letter ‘a‘ key is represented by the keycode of 65 using a keydown or keyup event and does not distinguish between upper and lowercase. If you use a keypress event, then you will need to use the ASCII code of 65 to check for uppercase A and 97 for lowercase a. For more information about the different keyboard events and how key codes work, click here. Note that some keys are not compatible with keyboard events in certain browsers. You can check out compatibility of browsers here.

A note about the addEventListener method

The useCapture parameter in the addEventListener method is optional. If used, it must be a boolean value. The boolean value will specify whether the event being used should be executed during the bubbling or capturing phase. A boolean value of true  means the event handler is executed during the capturing phase, while false (default option) means that the event handler is executed during the bubbling phase. To find out more about bubbling and capturing, click here.

JavaScript Quiz

Here is some code for a simple Quiz program written in JavaScript:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<title>Quiz</title>
 
<style>
div#test{ border:#000 1px solid; padding:10px 40px 40px 40px; }
</style>
 
<script type="text/javascript">
// pos is position of where the user in the test or which question they're up to
var pos = 0, test, test_status, question, choice, choices, chA, chB, chC, correct = 0;
// this is a multidimensional array with 4 inner array elements with 5 elements inside them
// if you don't want answers viewable in the code, then you should use PHP and mySQL database
var questions = [
 ["What is 5 + 4?", "10", "9", "7", "B"],
 ["What is 15 - 3?", "11", "13", "12", "C"],
 ["What is 6 x 4?", "24", "26", "21", "A"],
 ["What is 16 / 4?", "6", "3", "4", "C"]
 ];
// this get function is short for the getElementById function 
function get(x){
 return document.getElementById(x);
}
function renderQuestion(){
 test = get("test");
 if(pos >= questions.length){
 test.innerHTML = "<h2>You got "+correct+" of "+questions.length+" questions correct</h2>";
 get("test_status").innerHTML = "Test completed";
 // resets the variable to allow users to restart the test
 pos = 0;
 correct = 0;
 // stops rest of renderQuestion function running when test is completed
 return false;
 }
 get("test_status").innerHTML = "Question "+(pos+1)+" of "+questions.length;
 question = questions[pos][0];
 chA = questions[pos][1];
 chB = questions[pos][2];
 chC = questions[pos][3];
 test.innerHTML = "<h3>"+question+"</h3>";
 // the += appends to the data we started on the line above
 test.innerHTML += "<input type='radio' name='choices' value='A'> "+chA+"<br>";
 test.innerHTML += "<input type='radio' name='choices' value='B'> "+chB+"<br>";
 test.innerHTML += "<input type='radio' name='choices' value='C'> "+chC+"<br><br>";
 test.innerHTML += "<button onclick='checkAnswer()'>Submit Answer</button>";
}
function checkAnswer(){
 // use getElementsByName because we have an array which it will loop through
 choices = document.getElementsByName("choices");
 for(var i=0; i<choices.length; i++){
 if(choices[i].checked){
 choice = choices[i].value;
 }
 }
 // checks if answer matches the correct choice
 if(choice == questions[pos][4]){
 //each time there is a correct answer this value increases
 correct++;
 }
 // changes position of which character user is on
 pos++;
 // then the renderQuestion function runs again to go to next question
 renderQuestion();
}
window.addEventListener("load", renderQuestion, false);
</script>
</head>
<body>
<h2 id="test_status"></h2>
<div id="test"></div>
</body>
 
</html>

JavaScript calcalator

The code below shows how to make a simple calculator with JavaScript.

<html>
    <head>
        <title>My app</title>
    </head>
    <body>
        <div style="width:173px; background:lightblue">
            <form name="form">
                <input name="result"/></br></br>
                <input type="button" name="1" value="1" onClick="run('1')" style="width:40px"/>
                <input type="button" name="2" value="2" onClick="run('2')" style="width:40px"/>
                <input type="button" name="3" value="3" onClick="run('3')" style="width:40px"/>
                <input type="button" name="plus" value="+" onClick="runplus()" style="width:40px"/>
                </br>
                <input type="button" name="4" value="4" onClick="run('4')" style="width:40px"/>
                <input type="button" name="5" value="5" onClick="run('5')" style="width:40px"/>
                <input type="button" name="6" value="6" onClick="run('6')" style="width:40px"/>
                <input type="button" name="minus" value="-" onClick="runminus()" style="width:40px"/>
                </br>
                <input type="button" name="7" value="7" onClick="run('7')" style="width:40px"/>
                <input type="button" name="8" value="8" onClick="run('8')" style="width:40px"/>
                <input type="button" name="9" value="9" onClick="run('9')" style="width:40px"/>
                <input type="button" name="divide" value="/" onClick="rundivide()" style="width:40px"/>
                </br>
                <input type="button" name="0" value="0" onClick="run('0')" style="width:40px"/>
                <input type="button" name="." value="." onClick="runpoint()" style="width:40px"/>
                <input type="button" name="%" value="%" onClick="runpercent()" style="width:40px"/>
                <input type="button" name="multiply" value="x" onClick="runmultiply()" style="width:40px"/>
                </br>
                <input type="button" name="clear" value="C" onClick="runclear()" style="width:84px"/>
                <input type="button" name="calc" value="=" onClick="calculate()" style="width:84px"/>
                </br>
            </form>
        </div>
        <script>
            function run(number){
                document.form.result.value += number;
            }
            function runplus(){
                document.form.result.value += '+';
            }
            function runminus(){
                document.form.result.value += '-';
            }
            function runmultiply(){
                document.form.result.value += '*';
            }
            function rundivide(){
                document.form.result.value += '/';
            }
            function runpoint(){
                document.form.result.value += '.';
            }
            function runclear(){
                document.form.result.value = '';
            }
            function runpercent(){
                document.form.result.value += '*(100/1)';
            }
            function calculate(){
                var answer = eval(document.form.result.value);
                document.form.result.value = answer;
            }
        </script>
    </body>
</html>

 

JavaScript prompts (input boxes)

A prompt (or input box) is a popup box which asks the user a question and allows them to type and submit their answer in a textbox. The user must enter a value in the textbox or click on OK/cancel before they can continue interacting with the webpage.

These prompts can be intrusive and annoying so only use them when absolutely necessary. Forms are a better way of getting user input. The only data validation being used in this example is checking whether the input text box is empty or not.

Watch the video below and then scroll down to see the sample code.

Here is the code for the prompt box:

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="utf-8"/>
 <title>JavaScript Prompt Box</title>
 
</head>
<body>
 
 <script type="text/javascript">
 
 // This is a prompt box which asks for a name
 // The name is then displayed in the browser (only if a name is entered)
 
 var name=prompt("Please enter your name","Enter name here");
 if (name!=null) // this means if the name is NOT empty
 {
 message="Hello " + name + "! How are you today?";
 document.write(message);
 } 
 
 </script>
 
</body
</html>

Here are some questions to consider after using the sample code:

  • What happens when the user clicks on OK before replacing the default value with their own text value? Can this be changed?
  • What will be displayed in the message if the user clicks on Cancel? How can this be changed?
  • Can you think of a better way of asking the user a question and using their input, rather than using a JavaScript prompt?

Next tutorial: Using the HTML5 canvas tag to draw shapes

Alert boxes and confirmation boxes

Alert boxes are used to communicate messages to the user without taking them away from a web page. They are highly visible and must be acknowledged by clicking on ‘OK’ before the user can continue interacting with the web page.

Confirmation boxes also display a message but they give two options to the user: ‘OK’ and ‘Cancel’. Using JavaScript, you can program what will happen depending on which option the user chooses.

Alert boxes can tell the user that they have not completed a form correctly, and confirmation boxes can be used to ask the user to confirm something eg. you could ask the user if they accept terms and conditions of your site. If they click on OK, they can continue using the site, but if they click on Cancel then they will be redirected to another page.

Alert boxes and confirmation boxes can be annoying for the user so they should only be used when absolutely necessary. Watch the video below which explains both alert and confirmation boxes, and then scroll down to see the sample code for each type.

Here is the code for alert boxes:

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="utf-8"/>
 <title>Alert boxes</title>
 
</head>
<body>
 
 <script type="text/javascript">
 
 // This is an alert box which can be used to display messages in a popup window
 // It can be very annoying for users so use only when necessary
 // Alert boxes can be used to warn a user that they haven't completed a form properly
 alert("I am an alert box!");
 
 
 </script>
 
</body
</html>

Here is the code for confirmation boxes:

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="utf-8"/>
 <title>Confirmation boxes</title>
 
</head>
<body>
 
 <script type="text/javascript">
 
 // This is a confirmation box which gives two options: OK, and Cancel.
 var r=confirm("Press a button");
 if (r==true) {
 x = "You pressed OK!";
 } else {
 x = "You pressed Cancel!";
 }
 document.write(x); 
 
 
 </script>
 
</body
</html>

Next tutorial: JavaScript prompts (user input boxes)

Checkboxes and form validation

This video tutorial explains how to implement checkboxes in an HTML form and how to use JavaScript to validate the form data by checking whether at least one option has been selected. Remember, radio buttons are used when you want the user to select only one option or answer to a question, and checkboxes are used when you wish to allow the user to select more than one option (if more than one option is available).

Watch the video below and then scroll down to see the sample code.

Here is the sample code:

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="utf-8"/>
 <title>JavaScript - Checkboxes</title>
 <script type="text/javascript">
 
 function isChecked(){
 var India = document.getElementById('India').checked;
 var France = document.getElementById('France').checked;
 var Japan = document.getElementById('Japan').checked;
 var Sweden = document.getElementById('Sweden').checked;
 
 if(India==false && France == false && Japan==false && Sweden==false){
 alert('Please select a country!');
 return false;
 }
 else{
 return true;
 }
 }
 
 </script>
 
</head>
<body>
<form action="submission.html" method="get" onsubmit="return isChecked();">
 <p>Which countries would you like to visit most?</p>
 <input type="checkbox" name="countries" value="India" id="India"/>India <br/>
 <input type="checkbox" name="countries" value="France" id="France"/>France<br/>
 <input type="checkbox" name="countries" value="Japan" id="Japan"/>Japan<br/>
 <input type="checkbox" name="countries" value="Sweden" id="Sweden"/>Sweden<br/>
 <input type="submit" value="Submit"/>
</form>
 
</body>
</html>

Next tutorial: Alert boxes and confirmation boxes

Radio buttons and form validation

Forms allow users to submit data in many different ways. A range of form input elements are available including text boxes, checkboxes, radio buttons, and submit buttons. This video tutorial explains how to use radio buttons in a form and also how to use JavaScript to handle the form and validate the data which the user has provided.

Form validation checks whether an option has been selected before the form is submitted. If no option has been selected, then an alert message will tell the user to select an option and the form will not submit the data until an option has been selected.

Watch the video below and then scroll down to see the sample code.

Here is the sample code:

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="utf-8"/>
 <title>JavaScript - Radio buttons and form validation</title>
 <script type="text/javascript">
 
 // This file will use form validation for forms with radio buttons
 // Using 'name' in the radio buttons, puts these two radio button options in the same group (the same question)
 // Value is the text displayed next to the radio button that has been selected
 // ID identifies this element which can be used by Javascript code
 
 // The isChecked function checks to see if an option has been selected before continuing
 // .checked is a property of a radio button (that the radio button has been checked)
 
 function isChecked(){
 var checkedYes = document.getElementById('like').checked;
 var checkedNo = document.getElementById('dislike').checked;
 
 if(checkedYes == false && checkedNo == false){
 alert('You need to select an option!');
 return false;
 }
 else{
 return true;
 }
 }
 
 </script>
 
</head>
<body>
<form action="submission.html" method="get" onsubmit="return isChecked();">
 <p>Do you like coding?</p>
 Yes<input type="radio" name="coding" value ="Yes" id="like"/><br/>
 No<input type="radio" name="coding" value ="No" id="dislike"/><br/>
 <input type="submit" value="Submit"/>
</form>
 
</body>
</html>

Next tutorial: Checkboxes and form validation

Validating form data

In this tutorial, you will learn how to use JavaScript to validate form data. Form validation ensures that the correct form data has been provided by the user. For example, we can check if an email address contains the @ symbol, if a post code is a 4-digit number, if a date of birth is within a specified range, and that a username does not contain illegal characters such as a dollar sign or percent symbol.

In the example below, form validation is used to check that a username and password that is submitted is not empty (the user must enter something for both the username and password). It will not actually check if the username and password is correct though (that requires some server-side processing and a database – if we want to have a secure form).

Watch the video below and then scroll down to see the code.

Here is the code for the HTML file which contains the form and JavaScript form validation:

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="utf-8"/>
 <title>JavaScript - Form Validation</title>
 <script type="text/javascript">
 
 // Form validation is used to ensure that correct form data is provided by the user
 // This example uses the code from the previous tutorial.
 // Remember, there is no PHP/server-side file to use the form data yet.
 // This file uses the onsubmit event to run the checkInfo() function which will validate form data.
 
 function checkInfo(){
 var username = document.getElementById('username').value;
 var password = document.getElementById('password').value;
 
 // this checks if username or password is an empty string
 if(username=="" || password==""){
 alert('Please complete all fields');
 return false;
 // return false will stop the form from sending data
 }
 else{
 return true;
 // return true will allow the form data to be sent
 }
 
 }
 
 </script>
 
</head>
<body>
 
<form action="submission.html" method="post" onsubmit="return checkInfo();">
 Username: <input type="text" name="username" id="username"/>
 Password: <input type="password" name="password" id="password"/>
 <input type="submit" value="Login"/>
</form>
 
</body>
</html>

Here is the code for the submission.html  page (‘thank you’ page) the user sees after the form has been submitted:

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="utf-8"/>
 <title>JavaScript - Form data submitted</title>
 <script type="text/javascript">
 
 // This file is used after the form has been submitted for the Form Submission tutorials.
 // Do not delete this file
 
 </script>
 
</head>
<body>
 
<p>Thank you for submitting your data</p>
 
</body>
</html>

Next tutorial: Radio buttons and form validation

Submitting forms

This video tutorial explains how to create a form which can accept a username and password, and then submit the form data. The video only explains how to use the text and password input types in a form and provides an overview of the two methods of submitting form data: the post and get methods. The next tutorials will explain how to actually validate the data submitted in a form.

A form can be submitted using server-side code eg. PHP. A PHP file would be able to use the form data and send it to a database. In the action section of the form, you specify the file that is going to use the form data and the method (how the form data is used). As there is no PHP file for the example below, the form will not actually work properly, but this is just to show how it should be set out.

We can use the get method or the post method. The GET method is used for purposes such as a search engine, and attaches the information to the URL of the web page. For example, when using the search terms “cricket world cup” on Twitter, you will see the keywords attached to the URL of the search results page like this:

https://twitter.com/search?q=cricket%20world%20cup

The GET method is not secure as information that is submitted is highly visible in the URL. The POST method sends information to the server separately (and does not go in as part of the URL).  The POST method is the more secure method and is used for user logins, membership signup forms, and shopping carts.

Watch the video below and then scroll down the page to see the code.

Note that this tutorial does not actually involve any JavaScript – just an HTML form. JavaScript will be used in the next tutorial when we look at how to validate form data. Here is the code for this tutorial:

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="utf-8"/>
 <title>JavaScript - Submitting Forms</title>
 <script type="text/javascript">
 
 // A form can be submitted using server-side code eg. PHP.
 // A PHP file would be able to use the form data and send it to a database.
 // In the action section, you specify the file that is going to use the form data
 // and the method is how the form data is used. As there is no PHP file here
 // the form will not actually work properly, but this is how it should be set out.
 // We can use the get method or the post method. The post method sends information to the server
 // separately (and does not go in as part of the URL). POST is the more secure method eg. for a login.
 // The GET method is used for purposes such as a search engine.
 
 </script>
 
</head>
<body>
 
<form action="another_file.php" method="post">
 Username: <input type="text" name="username"/>
 Password: <input type="password" name="password"/>
 <input type="submit" value="Login"/>
</form>
 
</body>
</html>

Next tutorial: Validating form data

User input with forms

We will now start using forms to take user input. Forms include elements such as input text boxes, checkboxes, radio buttons, drop-down lists, and submit buttons.

In this tutorial, we will ask the user to enter their name and then display a personalised welcome message with their name included. In the first example, we will do do just that. In the second example, we will also hide the form once the user has entered and submitted their name.

Watch the video below and then scroll down to see the code.

Here is the code for the first example, where we ask for the user’s name and display a personalised welcome message. Notice that the form still remains after it has been submitted.

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="utf-8"/>
 <title>JavaScript - Forms</title>
 <script type="text/javascript">
 // This tutorial requires a basic understanding of forms in HTML
 // The form is created in the body section of the HTML page.
 
 function writeName(){
 var welcomeMsg = document.getElementById('welcome');
 var name = document.getElementById('name');
 
 welcomeMsg.innerHTML = "Welcome "+name.value+".<br/>";
 // We append .value to the end of name so that it sets the variable name
 // to be equal to a property which is the value, not the object.
 
 }
 
 </script>
 
</head>
<body>
 
<p id="welcome"></p>
<form>
 What is your name:<input type="text" id="name"/><br/>
 <input type="button" value="Submit" onclick="writeName();"/>
</form>
 
</body>
</html>

In the second example (below), once the user has entered their name and clicked on the ‘Submit’ button, the personalised message will be displayed and the form will also disappear.

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="utf-8"/>
 <title>JavaScript - Forms</title>
 <script type="text/javascript">
 // This tutorial requires a basic understanding of forms in HTML
 // The form is created in the body section of the HTML page.
 
 function writeName(){
 var welcomeMsg = document.getElementById('welcome');
 var name = document.getElementById('name');
 var formContent = document.getElementById('entername');
 
 welcomeMsg.innerHTML = "Welcome "+name.value+".<br/>";
 // We append .value to the end of name so that it sets the variable name
 // to be equal to a property which is the value, not the object.
 
 formContent.innerHTML = ""; // this removes the form text input box after name has been entered.
 
 }
 
 </script>
 
</head>
<body>
 
<p id="welcome"></p>
<form id="entername">
 What is your name:<input type="text" id="name"/><br/>
 <input type="button" value="Submit" onclick="writeName();"/>
</form>
 
</body>
</html>

Next tutorial: Treating text input from a form as an integer of float