Skip Headers
Oracle® Database Express Edition 2 Day Plus Application Express Developer Guide
Release 2.1

Part Number B25310-01
Go to Documentation Home
Home
Go to Book List
Book List
Go to Table of Contents
Contents
Go to Master Index
Master Index
Go to Feedback page
Contact Us

Go to previous page
Previous
Go to next page
Next
View PDF

9 How to Incorporate JavaScript into an Application

Adding JavaScript to a Web applications is a great way to add features that mimic those found in client/server applications without sacrificing all of the benefits of Web deployment. Oracle Application Express includes multiple built-in interfaces especially designed for adding JavaScript.

Remember that JavaScript is not appropriate for data intensive validations. For example, to verify that a name is contained within a large database table, you would need to pull down every record to the client, creating a huge HTML document. In general, complex operations are much better suited for server-side Application Express validations instead of JavaScript.

This tutorial describes some usage scenarios for JavaScript and includes details about how to implement them in your application.

This section contains the following topics:

Understanding How to Incorporate JavaScript Functions

There are two primary places to include JavaScript functions:

Topics in this section include:

Incorporating JavaScript in the HTML Header Attribute

One way to include JavaScript into your application is add it to the HTML Header attribute of the page. This is a good approach for functions that are specific to a page as well as a convenient way to test a function before you include it in the .js file.

You can add JavaScript functions to a page by entering the code into the HTML Header attribute on the Page Attributes page.

To add JavaScript code in the HTML Header attribute:

  1. On the Database Home Page, click the Application Builder icon.

  2. Select an application.

  3. Select a page.

  4. Click Edit Attributes.

  5. Scroll down to HTML Header.

  6. Enter code into HTML Header and click Apply Changes.

For example, adding the following would test a function accessible from anywhere on the current page.

<script type="text/javascript">
  function test(){
    window.alert('This is a test.');
  }
</script>

Including JavaScript in a .js File Referenced by the Page Template

In Oracle Application Express you can reference a .js file in the page template. This approach makes all the JavaScript in that file accessible to the application. This is the most efficient approach since a .js file loads on the first page view of your application and is then cached by the browser.

The following demonstrates how to include a .js file in the header section of a page template. Note the line script src= that appears in bold.

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
    <title>#TITLE#</title>
    #HEAD#
    <script src="http://myserver.myport/my_images/custom.js" type="text/javascript"></script>
</head>
<body #ONLOAD#>#FORM_OPEN#

About Referencing Items Using JavaScript

When you reference an item, the best approach is to reference by ID. If you view the HTML source of an Oracle Application Express page in a Web browser, you would notice that all items have an id attribute. This ID corresponds to the name of the item, not the item label. For example, if you create an item with the name P1_FIRST_NAME and a label of First Name, the id would be P1_FIRST_NAME.

Knowing the item ID enables you to use the JavaScript method getElementById() to get and set item attributes and values. The following example demonstrates how to reference an item by ID and display its value in an alert box.

<script type="text/javascript">
  function firstName(){    
    window.alert('First Name is ' + document.getElementById('P1_FIRST_NAME').value );
  }
 // or a more generic version would be
  function displayValue(id){    
    alert('The Value is ' + document.getElementById(id).value );
  }
</script>
 
  // Then add the following to the "Form Element Attributes" Attribute of the item:
  onchange="displayValue('P1_FIRST_NAME');"

Calling JavaScript from a Button

Calling a JavaScript from a button is a great way to confirm a request. Oracle Application Express uses this technique for the delete operation of most objects. For example, when you delete a button, a JavaScript message appears asking you to confirm your request. Consider the following example:

<script type="text/javascript">
  function deleteConfirm(msg)
  {
var confDel = msg;
if(confDel ==null)
  confDel= confirm("Would you like to perform this delete action?");
else
  confDel= confirm(msg);
  
if (confDel== true)
  doSubmit('Delete');
  }
</script>

This example creates a function to confirm a delete action and then calls that function from a button. Note that the function optionally submits the page and sets the value of the internal variable :REQUEST to Delete, thus performing the delete using a process that conditionally executes based on the value of request.

Note that when you create the button you would need to select Action Redirect to URL without submitting page. Then, you would specify a URL target such as the following:

confirmDelete('Would you like to perform this delete action?');

Creating a Client Side JavaScript Validation

Client side validations give immediate feedback to users using a form. One very common JavaScript validation is field not null. For example, you can create a function in the HTML Header attribute of a page and then call that function from an item.

Creating this type of JavaScript validation involves the following steps:

Topics in this section include:

About Accessing the HR Account

To complete this exercise, you need to log in to the sample database user account HR. Oracle Database Express Edition (Oracle Database XE) comes with a sample database user account called HR. This user owns a number of database tables in a sample schema that can be used to create applications for a fictional Human Resources department.

For security reasons, the HR user account is locked after installation. To learn how to unlock it, see "About the HR Account".

Create an Application on the EMPLOYEES Table

To create a new application on the EMPLOYEES table:

  1. On the Database Home Page, click the Application Builder icon.

  2. Click Create.

  3. For Method, select Create Application.

  4. For Name:

    1. In Name, enter a name that describes the application.

    2. For Application, accept the default.

    3. For Create Application, select From scratch.

    4. For Schema, accept the default.

    5. Click Next.

  5. Add a blank page, containing a report:

    1. Under Select Page Type, select Report and Form.

    2. From Table Name, select EMPLOYEES.

    3. Click Add Page.

    The new pages display at the top of the page. Next, change the name of page 2 to Update Form.

  6. To change the name of page 2:

    1. Under Create Application at the top of the page, click the page name Employees for page 2 as shown in Figure 9-1.

      Figure 9-1 Newly Created Pages

      Description of Figure 9-1 follows
      Description of "Figure 9-1 Newly Created Pages"

      The Page Definition appears.

    2. In Page Name, enter Update Form and click Apply Changes.

    3. Click Next.

  7. For Tabs, select One Level of Tabs and click Next.

  8. For Shared Components, accept the default, No, and click Next.

  9. For Attributes, accept the defaults for Authentication Scheme, Language, and User Language Preference Derived From and click Next.

  10. For User Interface, select Theme 2 and click Next.

  11. Click Create.

    The Application home page appears. Note the new application contains three pages:

    • 1 - EMPLOYEES

    • 2 - Update Form

    • 101 - Login

To view the application:

  1. Click the Run Application icon as shown in Figure 9-2.

  2. When prompted for a user name and password, enter hr for both and click Login.

    A standard report appears. To view the update form click either the Create button or Edit icon.

  3. Click Edit Application on the Developer toolbar.

Add a Function to the HTML Header Attribute

Next, you need to add a function to the HTML Header attribute on page 2 that displays a message when the Last Name field does not contain a value.

To add a function to the HTML Header attribute on page 2:

  1. On the Application home page, select 2 - Update Form.

    The Page Definition appears.

  2. Click Edit Attributes.

    The Edit Page attributes page appears.

  3. Scroll down to HTML Header. Note that HTML Header already contains a script.

  4. In HTML Header, scroll down and enter the following script after the </script> tag:

    <script type="text/javascript">
      function notNull(object){    
        if(object.value=="")
       alert('This field must contain a value.');
      }
    </script>
    
    
  5. Scroll back to the top of the page and click Apply Changes.

Edit an Item to Call the Function

Next, you need to edit the P2_LAST_NAME item to call the function. In the running form, the P2_LAST_NAME item displays as the Last Name field.

To edit the P2_LAST_NAME item to call the function:

  1. Navigate to the Page Definition for page 2 - Update Form.

  2. Under Items, select P2_LAST_NAME.

  3. Scroll down to Element.

  4. In HTML Form Element Attributes, enter the following:

    onblur="notNull(this);"
    
    
  5. Scroll back to the top of the page and click Apply Changes.

    The Page Definition appears.

  6. Navigate to page 1. Enter 1 in the Page field and click Go.

  7. Click the Run Page icon in the upper right corner.

  8. When the application appears, click Create.

    The Update Form appears.

  9. Position your cursor in the Last Name field and click Create. The following message appears:

    This field must contain a value.
    
    

Enabling and Disabling Form Elements

While Oracle Application Express enables you to conditionally display a page item, it is important to note that a page must be submitted for any changes on the page to be evaluated. The following example demonstrates how to use JavaScript to disable a form element based on the value of another form element.

First, you write a function and place it in the HTML Header attribute of the page containing your update form. Second, you call the function from an item on the page. The following example demonstrates how to add a JavaScript function to prevent users from adding commissions to employees who are not in the Sales Department (P2_DEPARTMENT_ID = 80).

Topics in this section include:

Add a Function the HTML Header Attribute

To add a function to the HTML Header attribute on page 2:

  1. Navigate to the Page Definition for page 2.

  2. On the Page Definition, click Edit Attributes.

    The Page Attributes appear.

  3. Scroll down to HTML Header.

  4. In HTML Header, scroll down and enter the following script after the last </script> tag:

    <script language="JavaScript1.1" type="text/javascript"> 
    function html_disableItem(nd,a){
         var lEl = document.getElementById(nd);
         if (lEl && lEl != false){
           if(a){
             lEl.disabled = false;
              lEl.style.background = '#ffffff';
            }else{
            lEl.disabled = true;
              lEl.style.background = '#cccccc';
             }}
         return true;}
    
     function disFormItems(){ 
      var lOptions = document.getElementById('P2_DEPARTMENT_ID').options
      var lReturn;
      for(var i=0;i<lOptions.length;i++){
         if(lOptions[i].selected==true){lReturn = lOptions[i].value;}
      }
      var lTest = lReturn == '80';
      html_disableItem('P2_COMMISSION_PCT',lTest); } 
    
     </script>
    
    
  5. Click Apply Changes.

Edit an Item to Call the Function

The next step is to edit the P2_DEPARTMENT_ID item and add code to the HTML Form Element Attributes attribute to call the function.

To edit the P2_DEPARTMENT_ID item to call the function:

  1. Navigate to the Page Definition for page 2.

  2. Under Items, select P2_DEPARTMENT_ID.

  3. Scroll down to Element.

  4. In HTML Form Element Attributes, enter the following:

    onchange="disFormItems()"
    
    
  5. Click Apply Changes.

Change P2_DEPARTMENT_ID to a Select List

To change the P2_DEPARTMENT_ID to display as a select list:

  1. Navigate to the Page Definition for page 2.

  2. Under Items, select P2_DEPARTMENT_ID.

  3. Under Display As, select Select List.

  4. Scroll down to List of Values.

  5. Under List of Values:

    1. From Display Null, select No.

    2. In List of Values definition, enter:

      SELECT department_name, department_id FROM departments
      
      
  6. Click Apply Changes.

Create a Call to the disFormItems Function

Finally, you need to create a call to the disFormItems function after the page is rendered to disable P2_COMMISSION_PCT if the selected employee is not a Sales representative. A good place to make this call would be from the Page HTML Body Attribute.

To create a call to the disFormItems function:

  1. Navigate to the Page Definition for page 2.

  2. Click Edit Attributes.

  3. Scroll down to On Load.

  4. In the Page HTML Body Attribute, enter the following:

    onload="disFormItems()"
    
    
  5. Click Apply Changes.

  6. Run the page by clicking the Run Page icon.

Figure 9-3 demonstrates the completed form. Note that Department ID displays as a select list. Also notice that the Commission Pct field is unavailable since the Department ID is Administration.

Figure 9-3 Revised Update Form

Description of Figure 9-3 follows
Description of "Figure 9-3 Revised Update Form"

Changing the Value of Form Elements

In the following example, there are four text boxes in a region. The fourth text box contains the sum of the other three. To calculate this sum, you add a JavaScript function to the HTML Header attribute and then call that function from the first three items

To call the function from the first three items:

  1. Navigate to the appropriate Page Definition.

  2. On the Page Definition, click Edit Attributes.

    The Page Attributes appear.

  3. In HTML Header, enter the following:

    <script type="text/javascript">
      function sumItems(){
        function getVal(item){
       if(document.getElementById(item).value != "")
         return parseFloat(document.getElementById(item).value);
       else
         return 0;
        }
        document.getElementById('P1_TOTAL').value = 
      getVal('P1_ONE') + getVal('P1_TWO') + getVal('P1_THREE');
      }
    </script>
    
    
  4. Click Apply Changes.

To call the function from all three items:

  1. Navigate to the appropriate Page Definition.

  2. For each item:

    1. Select the item name.

    2. Scroll down to Element.

    3. In HTML Form Element Attributes, enter:

      onchange="sumItems();"
      
      
    4. Click Apply Changes.