Press "Enter" to skip to content

Oracle Apex: Calculate Field Values Using JavaScript

In this tutorial, I will show you how to calculate field values using JavaScript in Oracle Apex.

To perform this task, we will create a function in JavaScript so that we can call it from multiple fields and then populate a field with the calculated value. To demonstrate this, I have created a page number 34 in Apex and the following are the fields on it.

  1. P34_SALARY
  2. P34_BONUS
  3. P34_TOTAL_SAL

On page 34, I have created the below JavaScript function to calculate Salary + Bonus as Total Salary in the Function and Global Variable Declare Section in Oracle Apex page:

JavaScript Function to Calculate Total Salary

function fnc_calcTotalSal() {
    var n_salary, n_bonus, n_total;
    
    n_salary = parseFloat($v("P34_SALARY"), 10) ? parseFloat($v("P34_SALARY"), 10) : 0;
    
    n_bonus = parseFloat($v("P34_BONUS"), 10) ? parseFloat($v("P34_BONUS"), 10) : 0; 
    
    n_total = n_salary + n_bonus;  
    
    $s("P34_TOTAL_SAL", parseFloat(n_total, 10));

}

In the above JavaScript function, it will check the P34_SALARY and P34_BONUS fields through the if ternary operator, that if it is a valid numeric value then OK, else it will assign the 0 value to the variable.

Then added the following JavaScript code in the Execute when Page Loads section, to make the P34_TOTAL_SAL field read-only.

document.getElementById('P34_TOTAL_SAL').readOnly = true;

Then I have created two dynamic actions to execute on the Lost Focus event for both P34_SALARY and P34_BONUS fields.

1. Dynamic Action for P34_SALARY

  • Event: Lost Focus
  • Action: Execute JavaScript Code
  • JavaScript Code: fnc_calcTotalSal();

2. Dynamic Action for P34_BONUS

  • Event: Lost Focus
  • Action: Execute JavaScript Code
  • JavaScript Code: fnc_calcTotalSal();

Below is the screenshot for the above settings:

Calculate field values using JavaScript in Oracle Apex.

Now it is ready to calculate the total salary and the following is the output:

Oracle Apex: Calculated Field output.

Reference:

Related Tutorial:

Oracle Apex: Format Number with Comma and Decimal Using JavaScript

Vinish Kapoor

Hi, I am a full stack developer and writing about development. I document everything I learn and help thousands of people. foxinfotech.in is created, written, and maintained by me; it is built on WordPress, and hosted by Bluehost. Connect with me on Facebook, Twitter, GitHub, and get notifications for new posts.

Comments are closed.