Develop a new think

If Condition

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.

Syntax if...else if statement.

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

Example

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.


 
--------

<script type="text/javascript>

function Compute(Operator)
{
  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 (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;
    }
  }
}

</script>

<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"
        onclick="Compute(this.value)"/>
      <input type="button" value="-" style="width:20px"
        onclick="Compute(this.value)"/>
      <input type="button" value="*" style="width:20px"
        onclick="Compute(this.value)"/>
      <input type="button" value="/" style="width:20px"
        onclick="Compute(this.value)"/>&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"
        onfocus="this.blur()"/></td>
</tr>
</table>

web counter