JavaScript | Example of if else if

JavaScript Example of if else if: In this tutorial, we will learn how if else if works in JavaScript? Here, we are writing a JavaScript example to demonstrate the use and working of if else if in JavaScript. By Pankaj Singh Last updated : July 30, 2023

JavaScript | if else if statement

In JavaScript, the if-else-if statement is used when you want to check more conditions if the given condition(s) is/are false. You can use else if to specify a new condition if the given condition is false. You can write as many else if statements to keep checking new conditions.

Consider the below syntax of if-else-if statement:

if (condition1) {
  //  Block-True-1
} else if (condition2) {
  //  Block-True-2
} else {
  //  Block-False
}

JavaScript example of if else if

In this example, we are reading salary of an employee and finding the discount based on given salary and discount rate.

Code (JS & HTML):

<!DOCTYPE html>

<HTML>
  <HEAD>
  
    <SCRIPT>
      function Calculate() {
        var sa = parseInt(document.getElementById("txta").value);
        
        var disc = 0.0;
        var np = 0.0;
        
        if (sa > 0) {
          if (sa <= 5000) {
            disc = sa * 0.05;
          } else if (sa <= 15000) {
            disc = sa * 0.15;
          } else if (sa <= 30000) {
            disc = sa * 0.25;
          } else {
            disc = sa * .4;
          }
      
          document.getElementById("txtb").value = "" + disc;
          var np = sa - disc;
          document.getElementById("txtc").value = "" + np;
        } else {
          alert('Invalid Sale Amount')
        }
      
      }
    </SCRIPT>
	
  </HEAD>
  
  <BODY>
    <h2>Nested Id : False ladder</h2>
    <hr />
    <table>
      <tr>
        <td>
          <label>Enter Sale Amount:</label>
        </td>
        <td>
          <input type="text" name="txta" id="txta" />
        </td>
      </tr>
      <tr>
        <td>
          &nbsp;
        </td>
        <td>
          <input type="button" value="Calculate Discount" onclick="Calculate()" />
        </td>
      </tr>
      <tr>
        <td>
          <label>Discount</label>
        </td>
        <td>
          <input type="text" name="txtb" id="txtb" readonly />
        </td>
      </tr>
      <tr>
        <td>
          <label>Net Pay</label>
        </td>
        <td>
          <input type="text" name="txtc" id="txtc" readonly />
        </td>
      </tr>
    </table>
  </BODY>
  
</HTML>

Output

if else if example | js

JavaScript Examples »



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.