Oracle APEX JavaScript Functions

JavaScript is the backbone of interactive web applications, and Oracle APEX provides a rich library of JavaScript functions that make your development work significantly easier. I've spent years working with these functions, and I can tell you that mastering them will transform how you build APEX applications. Let me walk you through the comprehensive set of JavaScript functions available in Oracle APEX, complete with practical examples you can use right away.

Understanding Oracle APEX JavaScript APIs

Before we dive into specific functions, you should understand how APEX organizes its JavaScript APIs. Everything lives under the apex namespace, which prevents conflicts with other JavaScript libraries. When you call an APEX function, you'll always start with apex. followed by the specific API and function name.

The beauty of APEX's JavaScript framework is that it handles browser compatibility for you. You don't need to worry about writing different code for Chrome versus Firefox. APEX takes care of those details behind the scenes.

Page and Item JavaScript Functions in Oracle APEX

These are the functions you'll use most frequently. They help you interact with page items, get and set values, and control page behavior.

apex.item()

This function returns an item object that you can use to interact with page items.

Description: Creates a reference to a page item, giving you access to all its methods and properties.

Example Usage:

// Get reference to item P1_EMPLOYEE_NAME
var empName = apex.item('P1_EMPLOYEE_NAME');

// Get the item's value
var nameValue = empName.getValue();

// Set the item's value
empName.setValue('John Smith');

// Disable the item
empName.disable();

// Enable the item
empName.enable();

// Hide the item
empName.hide();

// Show the item
empName.show();

apex.item().getValue()

Description: Retrieves the current value of a page item.

Example Usage:

// Get value from a text field
var salary = apex.item('P1_SALARY').getValue();

// Get value from a select list
var deptId = apex.item('P1_DEPARTMENT').getValue();

// Use the value in logic
if (parseFloat(salary) > 100000) {
    alert('High earner detected');
}

apex.item().setValue()

Description: Sets the value of a page item and optionally suppresses change events.

Example Usage:

// Set a text item value
apex.item('P1_EMPLOYEE_ID').setValue('12345');

// Set value without triggering change events
apex.item('P1_STATUS').setValue('Active', null, true);

// Set a date picker value
apex.item('P1_HIRE_DATE').setValue('2025-01-15');

apex.item().isEmpty()

Description: Checks if a page item has no value.

Example Usage:

// Check if required field is empty
if (apex.item('P1_EMAIL').isEmpty()) {
    apex.message.alert('Email address is required');
    return false;
}

// Conditional logic based on empty state
if (!apex.item('P1_PHONE').isEmpty()) {
    // Process phone number
}

apex.item().enable() and apex.item().disable()

Description: Enables or disables a page item, preventing user interaction when disabled.

Example Usage:

// Disable item based on condition
if (apex.item('P1_EMPLOYEE_TYPE').getValue() === 'Contractor') {
    apex.item('P1_BENEFITS').disable();
} else {
    apex.item('P1_BENEFITS').enable();
}

apex.item().show() and apex.item().hide()

Description: Shows or hides a page item on the page.

Example Usage:

// Hide/show based on selection
if (apex.item('P1_HAS_DEPENDENTS').getValue() === 'Y') {
    apex.item('P1_NUM_DEPENDENTS').show();
} else {
    apex.item('P1_NUM_DEPENDENTS').hide();
}

apex.item().setFocus()

Description: Sets keyboard focus to a specific page item.

Example Usage:

// Set focus to first empty required field
if (apex.item('P1_FIRST_NAME').isEmpty()) {
    apex.item('P1_FIRST_NAME').setFocus();
}

apex.item().setStyle()

Description: Applies CSS styling to a page item.

Example Usage:

// Highlight an item
apex.item('P1_ERROR_FIELD').setStyle('background-color', 'yellow');

// Remove styling
apex.item('P1_ERROR_FIELD').setStyle('background-color', '');

Server Process and AJAX Functions

These functions allow you to communicate with the server without refreshing the page, making your applications feel responsive and modern.

apex.server.process()

Description: Executes an AJAX process defined in your APEX application.

Example Usage:

// Call a process to calculate totals
apex.server.process(
    'CALCULATE_ORDER_TOTAL',
    {
        x01: apex.item('P1_QUANTITY').getValue(),
        x02: apex.item('P1_UNIT_PRICE').getValue()
    },
    {
        success: function(pData) {
            apex.item('P1_TOTAL').setValue(pData.total);
            apex.message.showPageSuccess('Total calculated successfully');
        },
        error: function(pMessage) {
            apex.message.showErrors([{
                type: 'error',
                location: 'page',
                message: 'Calculation failed: ' + pMessage
            }]);
        }
    }
);

apex.server.plugin()

Description: Calls an AJAX function defined in a plugin.

Example Usage:

// Call a custom plugin AJAX function
apex.server.plugin(
    'com.mycompany.validate_email',
    {
        x01: apex.item('P1_EMAIL').getValue()
    },
    {
        success: function(pData) {
            if (pData.isValid) {
                apex.message.showPageSuccess('Email is valid');
            } else {
                apex.message.alert('Invalid email format');
            }
        }
    }
);

apex.server.chunk.create()

Description: Creates a chunk object for uploading large files in parts.

Example Usage:

// Upload large file in chunks
var fileInput = document.getElementById('file-upload');
var file = fileInput.files[0];

var chunk = apex.server.chunk.create({
    success: function() {
        apex.message.showPageSuccess('File uploaded successfully');
    },
    error: function(error) {
        apex.message.alert('Upload failed: ' + error);
    }
});

chunk.upload(file);

Page Manipulation JavaScript Functions

These functions help you control the overall page behavior and navigation.

apex.page.submit()

Description: Submits the current page, optionally with a specific request value.

Example Usage:

// Submit page with default request
apex.page.submit();

// Submit with custom request
apex.page.submit('SAVE_RECORD');

// Submit with options
apex.page.submit({
    request: 'DELETE',
    validate: true,
    showWait: true
});

apex.page.validate()

Description: Validates all page items according to their validation rules.

Example Usage:

// Validate before custom processing
if (apex.page.validate()) {
    // Proceed with custom logic
    processData();
} else {
    apex.message.alert('Please fix validation errors');
}

apex.page.warnOnUnsavedChanges()

Description: Enables or disables the warning when users try to leave a page with unsaved changes.

Example Usage:

// Enable warn on unsaved changes
apex.page.warnOnUnsavedChanges('enable');

// Disable warn on unsaved changes
apex.page.warnOnUnsavedChanges('disable');

apex.page.cancelWarnOnUnsavedChanges()

Description: Temporarily cancels the unsaved changes warning for the next page transition.

Example Usage:

// Cancel warning for this navigation only
apex.page.cancelWarnOnUnsavedChanges();
apex.navigation.redirect('f?p=100:2:' + $v('pInstance'));

Control how users move through your application with these navigation functions.

apex.navigation.redirect()

Description: Redirects the browser to a different URL.

Example Usage:

// Redirect to another APEX page
apex.navigation.redirect('f?p=100:5:' + $v('pInstance'));

// Redirect to external URL
apex.navigation.redirect('https://www.example.com');

// Redirect with parameters
var url = apex.util.makeApplicationUrl({
    pageId: 10,
    itemNames: ['P10_ID'],
    itemValues: [123]
});
apex.navigation.redirect(url);

apex.navigation.dialog()

Description: Opens a page in a modal dialog.

Example Usage:

// Open dialog page
apex.navigation.dialog(
    'f?p=100:20:' + $v('pInstance') + ':::20:P20_ID:' + apex.item('P1_ID').getValue(),
    {
        title: 'Edit Employee',
        height: '600',
        width: '800',
        modal: true,
        dialog: null
    },
    'a-Dialog--uiDialog',
    $x('P1_ID')
);

apex.navigation.openInNewWindow()

Description: Opens a URL in a new browser window or tab.

Example Usage:

// Open report in new window
apex.navigation.openInNewWindow(
    'f?p=100:30:' + $v('pInstance'),
    'REPORT_WINDOW',
    'width=1000,height=800'
);

apex.navigation.popup.url()

Description: Opens a URL in a popup window with specific dimensions.

Example Usage:

// Open help in popup
apex.navigation.popup.url({
    url: 'f?p=100:999:' + $v('pInstance'),
    name: 'HELP_WINDOW',
    width: 600,
    height: 400
});

apex.navigation.popup.close()

Description: Closes the current popup window.

Example Usage:

// Close popup after save
apex.navigation.popup.close();

// Close popup and return value to parent
apex.navigation.popup.close({
    returnValue: apex.item('P1_SELECTED_VALUE').getValue()
});

Message and Notification Functions

Communication with users is essential, and these functions help you display messages effectively.

apex.message.showPageSuccess()

Description: Displays a success message at the page level.

Example Usage:

// Show simple success message
apex.message.showPageSuccess('Record saved successfully');

apex.message.showPageSuccess('Data exported');

setTimeout(function() {
apex.jQuery('.t-Body-alert').fadeOut(500, function() {
apex.message.clearErrors();
});
}, 5000);

apex.message.alert()

Description: Displays a modal alert dialog with a message.

Example Usage:

// Simple alert
apex.message.alert('Please select at least one record');

// Alert with callback
apex.message.alert('Are you sure?', function() {
    // Code to execute after user clicks OK
    processDelete();
});

apex.message.confirm()

Description: Displays a confirmation dialog with OK and Cancel buttons.

Example Usage:

// Confirm before delete
apex.message.confirm('Delete this record?', function(okPressed) {
    if (okPressed) {
        apex.server.process('DELETE_RECORD', {
            x01: apex.item('P1_ID').getValue()
        });
    }
});

apex.message.showErrors()

Description: Displays error messages on the page.

Example Usage:

// Show single error
apex.message.showErrors([{
    type: 'error',
    location: 'page',
    message: 'Invalid data entered',
    unsafe: false
}]);

// Show error for specific item
apex.message.showErrors([{
    type: 'error',
    location: 'inline',
    pageItem: 'P1_EMAIL',
    message: 'Email address is already in use',
    unsafe: false
}]);

apex.message.clearErrors()

Description: Clears all error messages from the page.

Example Usage:

// Clear all errors before validation
apex.message.clearErrors();

// Then run validation
if (apex.page.validate()) {
    // Process
}

apex.message.hidePageSuccess()

Description: Hides the page success message.

Example Usage:

// Hide success message after user takes action
apex.message.hidePageSuccess();

Region JavaScript Functions

Manage interactive regions, reports, and grids with these powerful functions.

apex.region()

Description: Returns a region object for interacting with APEX regions.

Example Usage:

// Get reference to a region
var empRegion = apex.region('employees');

// Refresh the region
empRegion.refresh();

// Get region data
var regionData = empRegion.getData();

apex.region().refresh()

Description: Refreshes the content of a region.

Example Usage:

// Refresh interactive report
apex.region('emp_report').refresh();

// Refresh with notification
apex.region('sales_chart').refresh();
apex.message.showPageSuccess('Data refreshed');

apex.region().widget()

Description: Returns the jQuery widget associated with the region.

Example Usage:

// Get Interactive Grid widget
var ig = apex.region('employee_grid').widget();

// Get grid model
var model = ig.interactiveGrid('getViews', 'grid').model;

// Get selected records
var selectedRecords = ig.interactiveGrid('getViews', 'grid').getSelectedRecords();

apex.region().call()

Description: Calls a method on the region's widget.

Example Usage:

// Call method on Interactive Grid
apex.region('employee_grid').call('getViews').grid.focus();

// Get actions for a region
var actions = apex.region('emp_report').call('getActions');

Interactive Grid Functions

Interactive Grids are powerful components, and these functions give you fine-grained control.

apex.region().call('getViews')

Description: Gets the views (grid, icon, detail, chart) of an Interactive Grid.

Example Usage:

// Get grid view
var gridView = apex.region('employee_grid').call('getViews', 'grid');

// Get the model
var model = gridView.model;

// Iterate through records
model.forEach(function(record) {
    var empName = model.getValue(record, 'EMPLOYEE_NAME');
    console.log(empName);
});
Oracle APEX JS function example console screenshot.

apex.region().call('getSelectedRecords')

Description: Gets the currently selected records in an Interactive Grid.

Example Usage:

// Get selected records
var gridView = apex.region('employee_grid').call('getViews', 'grid');
var selectedRecords = gridView.getSelectedRecords();

if (selectedRecords.length === 0) {
    apex.message.alert('Please select at least one record');
} else {
    // Process selected records
    selectedRecords.forEach(function(record) {
        var id = gridView.model.getValue(record, 'ID');
        console.log('Selected ID: ' + id);
    });
}

apex.region().call('getActions')

Description: Gets available actions for an Interactive Grid or Interactive Report.

Example Usage:

// Get actions
var actions = apex.region('employee_grid').call('getActions');

// Invoke a specific action
actions.invoke('save');

// Check if action is available
if (actions.lookup('edit')) {
    actions.invoke('edit');
}

Storage Functions

Store and retrieve data on the client side using these convenient functions.

apex.storage.getCookie()

Description: Retrieves the value of a browser cookie.

Example Usage:

// Get cookie value
var userPref = apex.storage.getCookie('USER_THEME_PREF');

if (userPref === 'dark') {
    // Apply dark theme
}

apex.storage.setCookie()

Description: Sets a browser cookie with the specified value.

Example Usage:

// Set cookie that expires in 30 days
apex.storage.setCookie('USER_THEME_PREF', 'dark', {
    expires: 30
});

// Set session cookie
apex.storage.setCookie('TEMP_DATA', 'value');

apex.storage.hasLocalStorageSupport()

Description: Checks if the browser supports HTML5 local storage.

Example Usage:

// Check for local storage support
if (apex.storage.hasLocalStorageSupport()) {
    // Use local storage
    localStorage.setItem('myKey', 'myValue');
} else {
    // Fallback to cookies
    apex.storage.setCookie('myKey', 'myValue');
}

Utility Functions

These helper functions solve common development challenges and make your code cleaner.

apex.util.showSpinner()

Description: Displays a loading spinner over a specific element or the entire page.

Example Usage:

// Show spinner on entire page
var spinner = apex.util.showSpinner();

// Show spinner on specific region
var regionSpinner = apex.util.showSpinner($x('employee_region'));

// Remove spinner after processing
setTimeout(function() {
    spinner.remove();
}, 2000);

apex.util.htmlBuilder()

Description: Creates an HTML builder object for constructing HTML strings safely.

Example Usage:

// Build HTML safely
var html = apex.util.htmlBuilder();
html.markup('<div')
    .attr('class', 'employee-card')
    .markup('>')
    .content('John Smith')
    .markup('</div>');

// Get the HTML string
var htmlString = html.toString();

apex.util.escapeHTML()

Description: Escapes HTML special characters to prevent XSS attacks.

Example Usage:

// Escape user input
var userInput = apex.item('P1_COMMENT').getValue();
var safeHtml = apex.util.escapeHTML(userInput);

// Display safely
$('#display_area').html(safeHtml);

apex.util.getTopApex()

Description: Returns the apex object from the top-level window, useful when working with modal dialogs.

Example Usage:

// Access parent window's APEX from dialog
var parentApex = apex.util.getTopApex();

// Refresh parent page region from dialog
parentApex.region('employee_list').refresh();

apex.util.makeApplicationUrl()

Description: Creates a properly formatted APEX application URL.

Example Usage:

// Build URL with parameters
var url = apex.util.makeApplicationUrl({
    appId: 100,
    pageId: 10,
    session: $v('pInstance'),
    request: 'EDIT',
    debug: 'YES',
    itemNames: ['P10_ID', 'P10_MODE'],
    itemValues: [123, 'EDIT']
});

apex.navigation.redirect(url);

apex.util.applyTemplate()

Description: Applies a template to data, replacing placeholders with actual values.

Example Usage:

// Apply template
var template = 'Welcome, #NAME#! Your ID is #ID#.';
var data = {
    NAME: 'John Smith',
    ID: '12345'
};

var result = apex.util.applyTemplate(template, data);
// Result: "Welcome, John Smith! Your ID is 12345."

// Display result
$('#welcome_message').html(result);

apex.util.delayLinger()

Description: Delays execution and shows a loading indicator if the operation takes longer than specified.

Example Usage:

// Show spinner if operation takes more than 100ms
apex.util.delayLinger.start('main', function() {
    apex.util.showSpinner();
});

// Perform async operation
apex.server.process('LONG_PROCESS', {}, {
    success: function(data) {
        apex.util.delayLinger.finish('main', function() {
            // Hide spinner
        });
    }
});

Event Functions

Handle and trigger custom events in your application.

apex.event.trigger()

Description: Triggers a custom event on a jQuery selector.

Example Usage:

// Trigger custom event
apex.event.trigger('#employee_region', 'employeeupdated', {
    employeeId: 123,
    action: 'update'
});

// Listen for custom event
$('#employee_region').on('employeeupdated', function(event, data) {
    console.log('Employee ' + data.employeeId + ' was ' + data.action);
    apex.region('employee_list').refresh();
});

apex.jQuery()

Description: Returns the jQuery version used by APEX, ensuring compatibility.

Example Usage:

// Use APEX's jQuery
var $ = apex.jQuery;

// Safely manipulate DOM
$('#my_element').addClass('highlight');

// Bind events
$('#my_button').on('click', function() {
    apex.message.alert('Button clicked');
});

Debug Functions

These functions help you troubleshoot and debug your applications.

apex.debug.info()

Description: Logs an informational message to the browser console when debug mode is enabled.

Example Usage:

// Log debug information
apex.debug.info('Processing employee data', {
    employeeId: apex.item('P1_EMP_ID').getValue(),
    timestamp: new Date()
});

// Log within a process
apex.debug.info('Starting validation');
if (apex.page.validate()) {
    apex.debug.info('Validation successful');
} else {
    apex.debug.info('Validation failed');
}

apex.debug.warn()

Description: Logs a warning message to the browser console.

Example Usage:

// Log warning
var age = parseInt(apex.item('P1_AGE').getValue());
if (age < 18) {
    apex.debug.warn('Age is below minimum requirement', age);
}

apex.debug.error()

Description: Logs an error message to the browser console.

Example Usage:

// Log error
try {
    // Some risky operation
    processData();
} catch (e) {
    apex.debug.error('Error processing data', e);
    apex.message.showErrors([{
        type: 'error',
        location: 'page',
        message: 'An error occurred. Please contact support.'
    }]);
}

apex.debug.trace()

Description: Logs a trace message with detailed information.

Example Usage:

// Trace function execution
apex.debug.trace('Entering calculateTotal function', {
    quantity: apex.item('P1_QTY').getValue(),
    price: apex.item('P1_PRICE').getValue()
});

var total = calculateTotal();

apex.debug.trace('Exiting calculateTotal function', {
    result: total
});

Dynamic Action Functions

Work with dynamic actions programmatically using these functions.

apex.da.resume()

Description: Resumes a dynamic action chain that was paused.

Example Usage:

// In a custom dynamic action
// Pause for async operation
this.action.resume = function() {
    apex.da.resume(this.resumeCallback, false);
}.bind(this);

// Perform async operation
setTimeout(this.action.resume, 2000);

apex.da.cancel()

Description: Cancels a dynamic action chain.

Example Usage:

// Cancel dynamic action based on condition
if (!apex.item('P1_CONFIRMED').getValue()) {
    apex.message.alert('Please confirm before proceeding');
    apex.da.cancel();
}

Session State Functions

Manage session state and temporary data.

$v() and $s()

Description: Legacy functions for getting and setting item values (still widely used).

Example Usage:

// Get value using $v
var empName = $v('P1_EMPLOYEE_NAME');

// Set value using $s
$s('P1_STATUS', 'Active');

// Note: apex.item().getValue() and setValue() are preferred in modern code

$x()

Description: Returns a DOM element by ID.

Example Usage:

// Get DOM element
var element = $x('P1_EMPLOYEE_NAME');

// Manipulate directly
element.style.backgroundColor = 'yellow';

// Add event listener
element.addEventListener('focus', function() {
    console.log('Element focused');
});

Collection Functions

Work with APEX collections from JavaScript.

apex.collection.create()

Description: Creates a new APEX collection.

Example Usage:

javascript

// Create collection via server process
apex.server.process('CREATE_CART_COLLECTION', {
    p_collection_name: 'SHOPPING_CART'
}, {
    success: function() {
        apex.message.showPageSuccess('Cart created');
    }
});

Actions API Functions

The Actions API provides a powerful way to work with actions in your application.

apex.actions.add()

Description: Adds a new action that can be invoked.

Example Usage:

// Add custom action
apex.actions.add([{
    name: 'export-to-excel',
    label: 'Export to Excel',
    action: function(event, focusElement) {
        // Export logic
        apex.server.process('EXPORT_DATA', {}, {
            success: function(data) {
                window.location.href = data.fileUrl;
            }
        });
    }
}]);

apex.actions.invoke()

Description: Invokes an action by name.

Example Usage:

// Invoke action
apex.actions.invoke('export-to-excel');

// Invoke with context
apex.actions.invoke('custom-save', {
    context: 'employee_form'
});

Oracle APEX Theme JavaScript Functions

Control theme-related functionality.

apex.theme.openRegion()

Description: Opens a collapsible region.

Example Usage:

// Open specific region
apex.theme.openRegion('employee_details');

apex.theme.closeRegion()

Description: Closes a collapsible region.

Example Usage:

// Close specific region
apex.theme.closeRegion('employee_details');

Best Practices for Using APEX JavaScript

Let me share some insights from my years of working with these functions. First, always use the apex namespace instead of global variables. This prevents conflicts and makes your code more maintainable.

When working with asynchronous operations like apex.server.process(), always include error handling. I've seen too many applications fail silently because developers only coded for the success scenario.

For debugging, make liberal use of apex.debug functions during development, but remember they only work when debug mode is enabled. This keeps your production console clean while giving you detailed information during development.

When manipulating page items, prefer apex.item() methods over direct DOM manipulation. This ensures APEX's internal state stays synchronized with the UI.

If you're building complex interactions, consider creating custom JavaScript modules that use these functions internally. This keeps your dynamic actions clean and makes your code reusable across multiple applications.

Always test your JavaScript in different browsers. While APEX handles most compatibility issues, custom code should still be tested across your target browser list.

Finally, document your custom JavaScript code. Future you (or your teammates) will thank you when maintaining the application six months later.

Conclusion

Mastering Oracle APEX's JavaScript functions opens up endless possibilities for creating rich, interactive applications. You don't need to use every function I've covered here, but knowing what's available helps you choose the right tool for each situation. Start with the basics like item manipulation and page submission, then gradually explore more advanced features like the Interactive Grid API and Actions framework.

Reference: APEX JavaScript API

See also: Oracle APEX CSS Classes

Vinish Kapoor
Vinish Kapoor

Vinish Kapoor is a seasoned software development professional and a fervent enthusiast of artificial intelligence (AI). His impressive career spans over 25+ years, marked by a relentless pursuit of innovation and excellence in the field of information technology. As an Oracle ACE, Vinish has distinguished himself as a leading expert in Oracle technologies, a title awarded to individuals who have demonstrated their deep commitment, leadership, and expertise in the Oracle community.

guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments