Lab 4 - JavaScript 2

JavaScript Examples and Exercises

Example 1 : Objects and their variables example

<html>
 
<head>
<script type="text/javascript">
function changeBgColor() {
  document.body.bgColor = "greenyellow";
  window.status = "background color changed";
}
</script>
</head>
<body>
<h1>JavaScript objects and variables</h1>
<p>
The following is an example of calling a function on an event - the onClick 
event on the hyperlink below to change the <code>bgColor</code> property of the <code>body</code>
<br /> 
<a href="#" onclick="javascript:changeBgColor()">Click to change background</a>
</p>
 
</body>
</html>

Example 2 : Using for loop to print a multiplication table

The following function uses a for loop to print a multiplication table for a number which is a parameter to the function

function printMultiplicationTable(number) {
  for (i = 1; i <= 10; i++){
    document.writeln("<br>" + number + " x " + i + " = " +(number * i));
  }
}

The above function can be called on any event such as an onClick on any object such as button, links etc. For example the code below shows the function being called on a onClick event for a link

<a href="#" onclick="javascript:printMultiplicationTable(4)">Click here to see 3 * 4</a>

Example 3 : Login Form Validation using JavaScript

<html>
    <head>
        <title>
            Form Validation Using JavaScript
        </title>
        <script type="text/javascript">
            function checkForm() {
                if (document.loginForm.user_name.value == "") {
                    alert("User name is blank - enter your username");
                    return false;
                }
                if (document.loginForm.password.value == "")
                    alert("Password is blank - enter your password");
            }
        </script>
    </head>
    <body>
        <div align="center">
        <form name="loginForm" action="#" onsubmit="checkForm()">
            <p>
                User Name : <INPUT TYPE="text" NAME="user_name">
            </p>
            <p>
                Password : <input type="password" name="password">
            </p>
            <p>
                <input type="submit" value="Login">
            </p>
        </form>
        </div>
    </body>
</html>

Example 4 : Form validation example - adding two numbers in a form

The input of the form is calculated before adding

The validation and calculation is done by the JavaScript function shown below - remember to place this in the head

<script type="text/javascript">
    function calculate() {
        a = document.calcForm.number1.value;
        b = document.calcForm.number2.value;
        if (document.calcForm.number1.value == "" || document.calcForm.number2.value == "") 
        {
             alert("Please enter a number");
             return false;
        }
        else if( isNaN(a) || isNaN(b)) {
             alert("Value is not an integer");
             return false;
        }
        else { 
              a = parseInt(a);
              b = parseInt(b);
              document.calcForm.result.value = (a + b);
              document.calcForm.result.focus();
              return false;
       }
   }
</script>

The form is given below:

<form name="calcForm" action="#" onsubmit="return calculate();">
    <p>
         Enter a number : <INPUT TYPE="text" NAME="number1">
    </p>
    <p>
         Enter another number : <input type="text" name="number2">
    </p>
    <p>
         Result : <input type="text" name="result">
    </p>
    <p>
        <input type="Submit" value="Calculate">
    </p>
</form>

Complete code with the JavaScript function and form in a web page

<html>
    <head>
        <title>
            Form Validation Using JavaScript - adding two numbers
        </title>
        <script type="text/javascript">
            function calculate() {
                a = document.calcForm.number1.value;
                b = document.calcForm.number2.value;
                if (document.calcForm.number1.value == "" || document.calcForm.number2.value == "") 
                {
                    alert("Please enter a number");
                    return false;
                }
                else if( isNaN(a) || isNaN(b)) {
                    alert("Value is not an integer");
                    return false;
                }
                else { 
                    a = parseInt(a);
                    b = parseInt(b);
                    document.calcForm.result.value = (a + b);
                    document.calcForm.result.focus();
                    return false;
                }
            }
        </script>
    </head>
    <body>
        <h2>Example of form validation - using JavaScript to add two numbers</h2>
        <div align="center">
        <form name="calcForm" action="#" onsubmit="return calculate();">
            <p>
                Enter a number : <INPUT TYPE="text" NAME="number1">
            </p>
            <p>
                Enter another number : <input type="text" name="number2">
            </p>
            <p>
                Result : <input type="text" name="result">
            </p>
            <p>
                <input type="Submit" value="Calculate">
            </p>
        </form>
        </div>
    </body>
</html>

Example 5 : Using external JavaScript

The above Example 4 can be rewritten to use an external JavaScript file (extension .js) as shown below.

The calculate.js is shown below:

function calculate() {
    a = document.calcForm.number1.value;
    b = document.calcForm.number2.value;
    if (document.calcForm.number1.value == "" || document.calcForm.number2.value == "") 
    {
             alert("Please enter a number");
             return false;
    }
    else if( isNaN(a) || isNaN(b)) {
            alert("Value is not an integer");
             return false;
    }
     else { 
            a = parseInt(a);
            b = parseInt(b);
            document.calcForm.result.value = (a + b);
            document.calcForm.result.focus();
            return false;
     }
}

And the HTML page will now change to

<html>
    <head>
        <title>
            Form Validation Using JavaScript - adding two numbers
        </title>
        <script type="text/javascript" src="calculate.js"></script>
    </head>
    <body>
        <h2>Example of form validation - using JavaScript to add two numbers</h2>
        <div align="center">
        <form name="calcForm" action="#" onsubmit="return calculate();">
            <p>
                Enter a number : <INPUT TYPE="text" NAME="number1">
            </p>
            <p>
                Enter another number : <input type="text" name="number2">
            </p>
            <p>
                Result : <input type="text" name="result">
            </p>
            <p>
                <input type="Submit" value="Calculate">
            </p>
        </form>
        </div>
    </body>
</html>

Exercises

Exercise 1: Write a JavaScript function that uses the Date object to print if it is morning, afternoon or night - use the Date class and its getTime() method

Exercise 2: Modify the above JavaScript and HTML in the above Example 4 to make a calculator and add the button to do the following operations: subtraction, multiplication, division and modulo.

Exercise 3: Create registration form webpage for your site with the following form fields - Name, User name, password and confirm password (both must be the same), year of birth and email, a checkbox for the use to select that he/she agree to the terms and conditions of the website.
Validations to do on this page:

  1. check if both the passwords are the same
  2. check if user name, password, confirm password, email are not empty and checkbox is selected
  3. Password and confirm password are the same
  4. Email is in the correct format
  5. Year of birth should be between 1900 and 2000 and must be four digits only

Solutions

Solution to Exercise 3 - JavaScript Validation Example for a Registration Form

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
 <head>
  <title>Lab 4 Exercise 3 JavaScript Validation Example</title>
  <script language="JavaScript">
    function checkForm() {
        if(document.regForm.fullName.value == "") {
            alert("Please enter your full name");
            return false;
        }
        if(document.regForm.userName.value == "") {
            alert("Please enter your user name");
                return false;
        }
        if(document.regForm.password1.value == "") {
            alert("Please enter your password");
            return false;
        }
        if(document.regForm.password2.value == "") {
            alert("Please enter your confirm password");
            return false;
        }
        if(document.regForm.password1.value != document.regForm.password2.value) {
            alert("Both the passwords must be the same");
            return false;
        }
        if(document.regForm.email.value == "") { 
            alert("Email cannot be blank");
            return false;
        }
        else {
            //now check if email address has valid format
            var email = document.regForm.email.value;
            if(email.indexOf("@") == 0 ||
                    email.indexOf("@") == (email.length -1)) {
                alert("@ is in the wrong place for your email");
                return false;
            }
            if(email.indexOf(".") == 0 ||
                                email.indexOf(".") == (email.length -1)) {
                alert(".(dot) is in the wrong place for your email");
                return false;
            }
        }
 
        if(document.regForm.year.value == "") {
            alert("year of birth cannot be blank");
            return false;
        }
        else {
            //check if year of birth is a number and four digits long
            var year = document.regForm.year.value;
            if(isNaN(year)) {
                alert("Year of birth must be a number");
                return false;
            }
            if(year.length < 4) {
                alert("Year of birth must be four digits only");
                return false;
            }
            //sanity checking
            year = parseInt(year);
            if (year < 1900 || year > 2000) {
                alert("Invalid age for registration!!!");
                return false;
            }
        }
 
        if(document.regForm.cbTAndC.checked == false) { 
            alert("Please agree to our terms and conditions");
            return false;
        }
 
    }
 
  </script>
 </head>
 <body>
     <h2> Registration Form</h2>
     <form name="regForm" action="#" onsubmit="checkForm()">
         <p> Full Name <input type="text" name="fullName">
         </p>
         <p> User Name <input type="text" name="userName">
                  </p>
         <p> Password <input type="password" name="password1">
                  </p>
         <p> Confirm Password <input type="password" name="password2">
                  </p>
         <p> Email <input type="text" name="email">
                  </p>
         <p> Enter your year of birth (4 digits for example 1980) 
                <input type="text" name="year">
         </p>
         <p>Agree to term and conditions 
            <input type="checkbox" name="cbTAndC">Yes
            </p>
         <input type="submit" value="Register">
         <input type="reset">
     </form>
 </body>
</html>
page_revision: 16, last_edited: 1258286072|%e %b %Y, %H:%M %Z (%O ago)
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License