Friday, July 20, 2012

Oracle Apex: Adding Up Tabular Form Column Values

Often with tabular form we get the requirement to tally up the total of one of the columns as user add/edit/delete rows of data.

In this post I'll show an easy & efficient way to achieve this using Javascript.

Step 1
Get your Javascript function to add-up the total ready. I have created a simple function which you can customise for your application. You will need to know the ID of the tabular form element you are trying to add.

All editable APEX tabular forms that are ID'ed like f0x_000x. You can find them out by using Firebug (chrome, firefox) or IE Developer Tool by hitting F12 as below. 


In my case I need add up the total in Salary column as I add rows or edit entries and add it to the Total Salary text field above the tabular form.

So here is the script. Find out the ID of your field and update the italics part. 

<script language="JavaScript" type="text/javascript">

 function addTotal()
 {
  var items = document.getElementsByName("f07"); // Tabular form column to add up
  
  $total = 0;
  $itemValue = 0;
  for (var i = 0; i < items.length; i++)
  {  
   // if non-numeric character was entered, it will be considered as 0, 
   // isNaN returns true if anything but number was entered
   if(isNaN(items[i].value) || items[i].value == null || items[i].value == "")
    $itemValue = 0;
   else
    $itemValue = parseFloat(items[i].value); // convert to number
   
   $total =$total+ $itemValue; // add up
  } 
  
  // $x sets the text field to be updated to the column total just calculated
  $x('P5_TOTAL_SALARY').value = $total;
 }
</script>

STEP 2. Test out the javascript.

Its a good idea to make sure your code works before putting it page attribute. So open up Firebug, go to the console tab and copy & paste the body of the function (everything in between the curly braces) and hit enter. If your Total Salary textfield gets updated as below then the function is working fine. 



STEP 3. 
Go to page attribute and in HTML Header & Body Attribute enter the code above.




STEP 4.
Next in page attribute, go to Javascript tab and  and add the newly created function addTotal() to where it says Execute when Page Loads. This will ensure that columns are totaled when page is loaded.





STEP 5. 
I will wrap that tabular form with a < DIV> tag and call this addTotal() function with onkeyup event. This will update the column total on every subsequent entries. 





With these steps, you should be able to add up the total of a tabular form column.


Here is how the it should behave if you implement the above steps correctly. 
http://apex.oracle.com/pls/apex/f?p=63895:5