Previous Contents Next
6. Decision Making

The if Statement

One of the most powerful features in scripting languages--and computer languages in general-- is the ability to make decisions. A script can be written to test some condition--some true or false situation--and to take alternative courses of action based on this evaluation. This means that a script can apply some crude intelligence to respond to different user needs.

Script decision making takes place through the JavaScript if statement. This statement takes the general form:

if (conditional expression) {
    ...do this...
}

That is, a conditional expression enclosed in parentheses--one that can be evaluated as true or false--is posed. If the evaluation of the expression turns out to be true, then the statements within the braces are executed; if the expression is false, the statements are not executed. In this case, then, either some processing takes place or it doesn't, depending on the results of the condition test.

An alternative form of the if statement is:

if (conditional expression) {
    ...do this... }
else {
    ...do this... }

Here, the script takes alternate courses of action depending on the condition test. If the conditional expression is evaluated as true, then the first set of statements is executed; if the conditional expression is evaluated as false, the second set of statements (following else) is executed. So, one of two different things is done, depending on the condition test.

The if statement--like most JavaScript statements--is written in free-format style. Therefore, you can format the statement a little differently if you choose, just making sure that the braces are paired correctly:

The following script present a simple example of decision making of the first type (if a condition is true, something happens; if the condition is false, it doesn't happen):


<SCRIPT>
function Display (Test)
{
    if (Test == "yes") {
        alert ("\nYou pressed button 'Press Me.'") }
}
</SCRIPT>


<FORM>
<INPUT TYPE=BUTTON VALUE="Press Me"

onclick = "var Switch = 'yes'; Display (Switch)" >
<INPUT TYPE=BUTTON VALUE="Press Me"

onclick = " var Switch = 'no'; Display (Switch)" >
</FORM>


In the first button, variable Switch is set to "yes"; in the second button it is set to "no." The buttons then call the Display (Test) function, passing this switch to it. (Recall from the discussion of functions that the names of the passed and received variables don't have to match; only the number and order of values must match.) The function Display (Test) evaluates whether the value passed to it is equal to the value "yes." If this evaluation is true, then an Alert box is displayed. If the evaluation is false, then the Alert box is skipped, which is why nothing happens when you click the second button.

The following script uses the second format of the if statement. Here, one of two alternatives happen:


<SCRIPT>
function Display (Test)
{
    if (Test == "first") {
        alert ("\nYou pressed the first button.") }
    else {
        alert ("\nYou pressed the second button.") }
}
</SCRIPT>


<FORM>
<INPUT TYPE=BUTTON VALUE="First Button"

onclick = "var Switch = 'first'; Display (Switch)" >
<INPUT TYPE=BUTTON VALUE="Second Button"

onclick = " var Switch = 'second'; Display (Switch)" >
</FORM>


The first button sets the Switch to "first"; the second button sets the Switch to "second." Then the function is called. If the value passed is equal to "first," then the first Alert box is displayed; if the value passed is not equal to "first" (it is equal to "second" when the second button is clicked), then the second Alert box is displayed. In this script, then, one of two things happen, unlike the previous script where something happened or not.

Nested If Statements

If statements can be nested. That is, if statements can appear within if statements, which can appear within if statements, and so on. Take a look at the following expansion of the previous script:

<SCRIPT>
function Display (Test)
{
    if (Test == "first") {
        alert ("\nYou pressed the first button") }
    else {
             if (Test == "second") {
                alert ("\nYou pressed the second button") }
            else {
                    if (Test == "third") {
                        alert ("\nYou pressed the third button") } } }
}
</SCRIPT>

<FORM>
<INPUT TYPE=BUTTON VALUE="First Button"

onclick = "var Switch = 'first'; Display (Switch)" >
<INPUT TYPE=BUTTON VALUE="Second Button"

onclick = "var Switch = 'second'; Display (Switch)" >
<INPUT TYPE=BUTTON VALUE="Third Button"

onclick = "var Switch = 'third'; Display (Switch) " >
<INPUT TYPE=BUTTON VALUE="Fourth Button"

onclick = "var Switch = 'fourth'; Display (Switch) " >
</FORM>


Now, several condition tests are made by the function. If the value of Test is "first," then the first Alert box is displayed and the script ends; the condition is satisfied, so the remaining else tests are skipped. If, however, the value of Test is not equal to "first," then the else clause is evaluated. If the value of Test is "second," then the second Alert box is display and the script ends with the condition being satisfied. Otherwise, the next else is evaluated. If the value of Test is "third," then the third Alert box is displayed and the script ends. If, however, Test is not equal to "third," the Alert is skipped and the script ends with no Alert box being display (as happens with the fourth button).

With multiple levels of nesting it can get confusing keeping track of which else goes with which if, and which closing } is paired with which opening { . With multiple condition tests, however, this is the most efficient way of coding since, once a condition is satisfied, the remaining statements of the function are skipped. The browser doesn't waste its time evaluating the remaining conditions once one is found true. Still, you do not have to nest if statements to accomplish the same purposes. You can code the above function as separate if statements if you're willing to live with the (possibly minor) inefficiencies over (possibly increased) clarity:

<SCRIPT>
function Display (Test)
{
    if (Test == "first") {
        alert ("\nYou pressed the first button") }
    if (Test == "second") {
        alert ("\nYou pressed the second button") }
    if (Test == "third") {
        alert ("\nYou pressed the third button") }
}
</SCRIPT>

The inefficiency results in all conditions being evaluated even when the first one or the second one is satisfied--it still checks the third.

Boolean Values

In the previous scripts we have passed string values to a function. It has tested the strings "first," "second," and "third," for instance. This is okay to do, but there is another type of test that can be used, based on Boolean values. Recall, earlier we introduced three types of variables: numeric, string, and Boolean. Boolean variables can take on one of two values: true or false. Since if tests are true-false tests, we can use Boolean values to set up the condition to be tested. Here is a simple example:

<SCRIPT>
function Evaluate (Test)
{
    if (Test) {
        alert ("\nSo, it's true!??!") }
}
</SCRIPT>

<FORM>
<INPUT TYPE=BUTTON VALUE="Click Me"

onclick = "var Switch = true; Evaluate (Switch) " >
</FORM>


When the button is clicked, the onclick handler sets variable Switch to the Boolean value true, then passes the Switch to the function. The function receives the variable as Test, which it evaluates. Since any condition test is resolved to a true or false condition, and since the Boolean value true is the value of Test, then the condition is true and the Alert box is displayed. This is the same result that would occur if the button set Switch = "true" and the function tested if (Test = "true"). Just two ways of doing the same thing.

The Confirm Message

A Boolean condition test is used with Confirm messages. On the previous page the confirm statement was introduced as a means of communicating with users. It presents a dialog box with two buttons: "OK" and "Cancel":

The confirm statement calls a built-in JavaScript function that returns the Boolean value true if the users clicks the "OK" button, and the value false if the user clicks the "Cancel" button. Therefore, you can test this returned value and have the script perform alternate processing depending on which button was clicked. This is done in the following script that governs the above button:


<SCRIPT>
function BGColor()
{
    if (confirm ("Are you sure you want a black background?") ) {
        document.bgColor="black" }
    else {
        document.bgColor="white" }
}
</SCRIPT>

<FORM>
<INPUT TYPE=BUTTON VALUE="Background Color"
onclick="BGColor()">
</FORM>


The confirm statement itself is the condition test! This is because its execution returns a Boolean value, and we can test that value. If the user clicks the "OK" button, the returned value is true and the background is set to black; if the user clicks the "Cancel" button, the returned value is false and the background is set to white. (We'll discuss the syntax of the document.bgColor property later.) In this example you must use a Boolean test since that is what JavaScript returns, and you can't change that.

Conditional Operators

In previous examples we used one kind of condition test: the test for equality. Functions checked to see if one value was equal to (==) another value and we didn't explain the use of the strange equal sign or whether other tests were available.

There are a number of different condition tests that can be made using the operators shown in the accompanying table:

Operator Comparison
==
Tests whether one value is equal to another value.
!=
Tests whether one value is not equal to another value.
<
Tests whether one value is less than another value.
>
Tests whether one value is greater than another value.
<=
Tests whether one value is less than or equal to another value.
>=
Tests whether one value is greater than or equal to another value.
?
Tests a condition and assigns a value to a variable:

      X = (condition test) ? Y : Z

means that if the condition test is true, then assign Y to X; if the condition test is false, assign Z to X. The condition test uses the previous operators.


 

Regardless of the conditional operator used, the result evaluates to either true or false. You also need to make sure that you don't confuse the conditional operator that tests for equality (==) with the assignment operator (=).

Logical Operators

Sometimes you need to combine condition tests. For instance, you might need to know if a numeric value is in a particular range; that is, whether the number is greater than one value and less than another value. Or, you might want to see if the number is outside a range by testing whether it is less than one value or greater than another value. These kinds of combination tests are made possible by using logical (Boolean) operators to form multiple comparisons:

Operator Effect
&&
And operator.

       if ( (condition) && (contition) )

The first condition and the second condition must be true for the expression to be true.

||
Or operator.

       if ( (condition) || (condition) )

The first condition or the second condition must be true for the expression to be true.

!
Not operator.

       if ( ! (condition) )

The condition is set to its opposite; i.e., a true condition is set to false and vice-versa.


 

Applying these operators in the range tests posed above, here are some tests to see if a value passed to a function is within the range 100 to 200:

<SCRIPT>

function InRange (Value) {
    if (Value >= 100) && (Value <= 200) {
        alert ("The number is in the range.") } }

function OutRange (Value) {
    if (Value < 100) || (Value > 200) {
        alert ("The number is out of range.") } }

function OutRange2 (Value) {
    if ( ! ( (Value >= 100) && (Value <= 200) ) {
        alert ("The number is out of range.") } }

</SCRIPT>

You can combine more than two tests in a conditional expression. You just need to make sure your logic (and parentheses) are correct. Logical operations are evaluated from the inside parentheses outward, just like in arithmetic expressions.

Checking Forms

If your web page includes a fill-in form, then you'll probably need to verify the information typed by the user before submitting the form for processing. Such verification normally involves a series of if statements to check for things such as empty fields, numbers outside valid ranges, proper lengths of text fields, and the like. The following form and accompanying script illustrate this use of if statements:

Application for Membership


Please respond to all items:

Your Name
Your Age
Membership Type

 

<SCRIPT>
function Validate ( )
{
    var Name = document.Application.TheName.value
    var Age = document.Application.TheAge.value
    var Member = document.Application.TheType.selectedIndex

    /* Check for name */
    if ( Name == '' ) {
        alert ("\nYour must enter a name.")
        return false }

    /* Check age */
    if ( Age == '' ) {
        alert ("\nYour must enter your age.")
        return false }
    else {
        if ( (Age < 18 || Age > 100) ) {
            alert ("\nYour age must be between 18 and 100.")
            return false } }

    /* Check membership */
    if ( Member == "0" ) {
        alert ("\nPlease choose a membership category.")
        return false }

    /* If all tests are passed */
    return true
}
</SCRIPT>

<FORM NAME="Application" onsubmit="return Validate ( )" >
<CENTER><H3>Application for Membership</H3></CENTER>
<HR SIZE=1>
Please respond to all items:
<P>
<INPUT TYPE=TEXT NAME="TheName" SIZE=19 >Your Name<BR>
<INPUT TYPE=TEXT NAME="TheAge"SIZE=19> Your Age<BR>
<SELECT NAME="TheType">
    <OPTION VALUE="0">
    <OPTION VALUE="1">Full Member
    <OPTION VALUE="2">Associate Member
    <OPTION VALUE="3">Half-Full Member
    <OPTION VALUE="4">Half-Empty Member
</SELECT>
Membership Type <BR>
<P>
<INPUT TYPE=SUBMIT NAME="Submit">
</FORM>


Let's take a look at the form first. The form is submitted for processing with a SUBMIT button (<INPUT TYPE=SUBMIT>). This is usually a special button used in forms processing, and is normally associated with a CGI (Common Gateway Interface) script residing on the server to which the form data is passed. Instead, in this instance, the form is being submitted to the JavaScript script for validation. This is done through special coding of the <FORM> tag:

<FORM NAME="Application" onsubmit="return Validate ( )" >

by adding a NAME attribute along with an onsubmit event handler. This handler is activated by the SUBMIT button even though it appears in the <FORM> tag.

The event handler,

onsubmit = "return Validate ( )"

sends the form to the Validate ( ) function. The return parameter awaits a true or false Boolean value from the function. If true is returned, the form normally would be forwarded for processing to the CGI script (although not in this example); if false is returned, the form is not forwarded. All that you need to understand is that the form is sent to the Validate ( ) function and a Boolean value is returned.

The first thing that takes place in the script is that the three data values from the form are assigned to variables:

var Name = document.Application.TheName.value
var Age = document.Application.TheAge.value
var Member = document.Application.TheType.selectedIndex

This step is not really necessary but it makes the script less cumbersome with the shorter variable names. The assignment in the first line points to the data value of the field named TheName from the form named Application located in the current document. (These naming conventions are covered in the topics on objects, properties, and methods. For present, you just need to be aware that the form fields TheName, TheAge, and TheType are assigned to variables.)

The first check made is to verify that the user entered something in the name field:

/* Check for name */
if ( Name == "" ) {
    alert ("\nYour must enter a name.")
    return false }

The if statement checks for a null value (""). If the user has not entered a name, an Alert box announcing that fact is displayed and Boolean false is returned, ending the script. If false is returned, the form is not submitted for processing. If, on the other hand, there are characters in the field, the script proceeds to the next set of checks:

/* Check age */
if ( Age == "" ) {
    alert ("\nYour must enter your age.")
    return false }
else {
    if ( (Age < 18 || Age > 100) ) {
        alert ("\nYour age must be between 18 and 100.")
         return false } }

First, the age is checked to see if a value has been entered. If the script finds a null value (""), then an Alert box is displayed and false is return, ending the script. If there is an age in the field, it is then checked for being in the proper range. If the number typed is less that 18 or greater than 100, an Alert box is displayed, false is returned, and the script ends. If, however, a proper age has been typed, the script proceeds to the final check:

/* Check membership */
if ( Member == "0" ) {
    alert ("\nPlease choose a membership category.")
    return false }

The value returned from a list of <SELECT> tag options is the index number of the option selected. The first <OPTION> is index number 0, the second option is number 1, and so forth through all of the options on the form. Therefore, the script needs to check this number to see if a blank option (the first one in the <OPTION> list) was selected. So, if the value is 0, then no membership category was selected and the script ends after displaying an Alert box and returning false.

As long as a validity check is passed, the script proceeds to the next check. If all checks are passed, the script ends up at the last statement: return true. If it gets this far, then a true value is return to the onsubmit handler in the <FORM> tag. At that point, the form would be submitted to a CGI script for processing.

There is one glaring hole in the validity checks. JavaScript does not provide an easy way to check whether a value is numeric. Therefore, if the user enters a non-numeric character in the age field, the script blows up! It tries to compare a non-number with a number (18 or 100) and just can't do it. (You can try this if you want.) To close this loophole requires you to write you own routine to test for non-numeric characters, something we will do on the next page covering loops and arrays.


Previous Contents Next