More JavaScript

JavaScript Variables

Study (and perhaps run) the following example:


<html>
<head>
<title>Javascript Labs</title>
</head>
<body>

<script>
   course_name = "Adaptive Web Technology";
   string_name = "This is the";
   str_to_display = string_name + " " + course_name + " course." ;
   document.write(str_to_display);
</script>

</body>
</html>

Run it!

Comparing variable values:

if (course_name=="Adaptive Web Technology") {
    document.write("Success");
}
else {
    document.write("Failed");
}

Some operators are:

==   Equal to
!=   Not equal to
<Less than
>Greater than
<=Less than or equals
>=Greater than or equals

Creating Popup Boxes

It is possible to create three different kinds of popup boxes through javascript.

  1. Alert
  2. Confirm
  3. Prompt

When a confirm box is presented and the user clicks on OK the value returned is true. When the user clicks on CANCEL the value returned is false.

Consider the following:

if ( confirm("Do you agree with the terms and conditions of the agreement") )
{
    alert("You agree and can continue setup");
}
else
{
    alert("You disagreed, exiting setup");
}

Using if...else Structures

As we know, different browsers show the same web page differently. At such times we need to be able to bring up different pages to show accordingly depending upon the type of browser being used.

The syntax of the if else structure would be:

if (condition)
{
        action...
}
else
{
        action...
}
Now let's take a look at some sample javascript showing the if else structure, which you might want to test. Here we assume a 24 hour time format.
if (time >= 1200)
{
    alert ("It is after noon.");
}
else
{
    alert ("It is morning.");
}

In the example above, we would need to store a value in the variable 'time' which would check the condition and then take the necessary action.

We can also have nested if else structures, so that we can check for a variety of conditions in a nested fashion. Here's how:

if (condition1)
{
        action1...
}
else if (condition2)
{
        action2...
}
else if (condition3)
{
        action3...
}
...
else
{
        actionN...
}
Here's an example of nesting if else structures:

if (gpa > 3.5)
{
    alert ("You are a very good student.");
}
else if (gpa > 2.9)
{
    alert ("You are a good student.");
}
else if (gpa > 2.5)
{
    alert ("You have an OK GPA.");
}
else 
{ 
    alert ("You really need to put in more effort.");
}
In the example above we would have a value stored in the variable 'gpa' which we would use in evaluating the various conditions of the if else structure.

You can also use and, or, and not to check for multiple conditions in the if statements.