The if StatementOne 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) { 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) { 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>
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>
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 StatementsIf 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>
<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> 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 ValuesIn 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>
<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 MessageA 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>
<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 OperatorsIn 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:
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 OperatorsSometimes 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:
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> 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 FormsIf 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:
<SCRIPT>
<FORM NAME="Application" onsubmit="return Validate ( )"
>
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 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 */ 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 */ 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 */ 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.
|