Web Development Tutorials




  
  

The if...else...if Statement

The if...else if construct can be used to test multiple conditions without having to nest separate if...else statements inside one another. These multiple tests are formed by using as many parallel if...else if condition tests as there are conditions to be tested.

if (conditional expression1) {
  do this...
} else if (conditional expression2) {
  do this...
} else if (conditional expression3) {
  do this...
}
 ...
[else {do this...}]

Figure 4-9. General format for if...else if statement.

If conditional expression1 is evaluated as true, then the set of statements enclosed within the first set of braces is executed; if the expression is evaluated as false, then conditional expression2 is evaluated. If this expression is evaluated as true, then the set of statements enclosed within the second set of braces is executed; if the expression is evaluated as false, then conditional expression3 is evaluated, and so forth for as many tests as are coded. The final, optional, else condition is provided in case none of the previous tests is evaluated as true.

The following script is an example of the if...else if form of condition testing in which one of four actions - addition, subtraction, multiplication, or division - is taken on entered numbers depending on which button is clicked.


 
--------

Figure 4-10. Testing conditions with if...else if statements.

window.onload = init;

function init() {
  var BtnAdd = document.getElementById("");
  var BtnSub = document.getElementById("");
  var BtnMul = document.getElementById("");
  var BtnDiv = document.getElementById("");

  BtnAdd = Compute;
  BtnSub = Compute;
  BtnMul = Compute;
  BtnDiv = Compute;

  var txtAnswer = document.getElementById("");

  txtAnswer.onfocus = blur();
}

function Compute() {
  var No1 = document.getElementById("Number1").value;
  var No2 = document.getElementById("Number2").value;
  var Answer = document.getElementById("Answer");
  
  if ( isNaN(No1) || isNaN(No2) || No1 == "" || No2 == "" ) {
    alert("Please enter numbers in the text boxes.");
  } else {
    if (this.value == "+") {
      Answer.value = parseFloat(No1) + parseFloat(No2);
    } else if (this.value == "-") {
      Answer.value = No1 - No2;
    } else if (this.value == "*") {
      Answer.value = No1 * No2;
    } else if (this.value == "/") {
      Answer.value = No1 / No2;
    }
  }
}

<table border="0" cellpadding="0" cellspacing="0">
<tr>
  <td></td>
  <td><input id="Number1" type="text" 
        style="width:50px; text-align:right"></td>
<tr>
  <td><input type="button" value="+" style="width:20px" 
        id="BtnAdd">
      <input type="button" value="-" style="width:20px" 
        id="BtnSub">
      <input type="button" value="*" style="width:20px" 
        id="BtnMul">
      <input type="button" value="/" style="width:20px" 
        id="BtnDiv">&nbsp;
  </td>
  <td><input id="Number2" type="text" 
       style="width:50px; text-align:right"/></td>
</tr>
<tr>
  <td></td>
  <td>--------</td>
</tr>
<tr>
  <td style="text-align:right">=&nbsp;</td>
  <td><input id="Answer" type="text" style="width:50px; text-align:right"
        id="txtAnswer"></td>
</tr>
</table>

Listing 4-8. Code to test conditions with if...else if statements.

The clicked button calls the Compute() function, passing the value (this.value) of the button. The function receives the passed value ("+", "-", "*", or "/") as argument Operator, which indicates the operation to perform.

First, the script saves the values of the two input textboxes as variables No1 and No2; it saves a reference to the output textbox as variable Answer. The reason for assigning these references to variables is to simplify the coding with short variable names rather lengthy references.

An initial test is made to ensure that the entered values are numbers. If either of the values is not a number or if either of the values is null, an error message is displayed.

if ( isNaN(No1) || isNaN(No2) || No1 == "" || No2 == "" ) {
   alert("Please enter numbers in the text boxes.");
}

With assurance that only numbers are entered into the textboxes, the script tests the value the current button referenced bythis.value to determine which arithmetic operation to carry out.

if (Operator == "+") {
   Answer.value = parseFloat(No1) + parseFloat(No2);
} else if (Operator == "-") {
   Answer.value = No1 - No2;
} else if (Operator == "*") {
   Answer.value = No1 * No2;
} else if (Operator == "/") {
   Answer.value = No1 / No2;
}

The result of the operation is assigned to Answer.value, the saved shortcut reference to document.getElementById("Answer").value. Note that for addition the two input values are converted to numbers with parseFloat(); otherwise they would be concatenated since textbox values are strings. No explicit conversion is needed for the other operations since JavaScript automatically converts them to numbers if the input string is composed only of numerals.

It is notable in this example that the Operator argument is an actual arithmetic operator. This operator, along with the input values, can be concatenated to compose an arithmetic expression that is evaluated with the eval() method. This alternative to the above script is shown below.

function Compute() {
   var No1 = document.getElementById("Number1").value;
   var No2 = document.getElementById("Number2").value;
   var Answer = document.getElementById("Answer");
  
   if ( isNaN(No1) || isNaN(No2) || No1 == "" || No2 == "" ) {
      alert("Please enter numbers in the text boxes.");
   } else {
      Answer.value = eval(parseFloat(No1) + this.value + parseFloat(No2));
   }
}

Listing 4-9. Using eval() method to evaluate an arithmetic expression.

The value of variable No1 is concatenated with the value of this (the reference to the current button) and with the value of variable No2. If, for example, the numbers 5 and 7 are entered into the textboxes and the "+" button is clicked, the concatenation produces the string "5 + 7", which is a valid arithmetic expression. This expression can be evaluated with eval() to produce the calculated result for assignment to the output textbox.


TOP | NEXT: switch() Statements