XForms/Dynamically Load JavaScript
Motivation
editSometime XForms data elements don't do everything you need. This is especially true for exception handling. When this happens you can dynamically load a JavaScript program to handle the required functionality.
This example will use the XForms load element. But unlike most JavaScript functions, it will not be loaded into the browser until it is needed.
Sample Program
editHere is an example of using the load element within an XForms trigger:
First you will need a small JavaScript function to test like the following:
<script type="text/javascript">
var MyJavaScript=function(){
alert('Hello From JavaScript');
}
</script>
Then you can call this JavaScript function using the Load function within a trigger:
<xf:trigger>
<xf:label>Run JavaScript</xf:label>
<xf:action ev:event="DOMActivate">
<xf:load resource="javascript:MyJavaScript()" />
........
</xf:action>
</xf:trigger>
You can also pass data from an XForms instance by using the following example:
function myjavascriptfunction(id) {
// We get the instance element
var instanceElement = document.getElementById(id);
if (instanceElement!=null) {
// XForms exposes the retrieval of the instance document from the model element which *should*
// be the parent for the instance element.
var instance = instanceElement.parentNode.getInstanceDocument(id);
}
}
When the user selects this trigger the JavaScript function my-javascript-function will be dynamically loaded into the XForm application and executed.
References
editThis program was inspired by the following example posted by Nicholas Chase, a Freelance writer with Backstop Media.
The link is here: IBM XForms Tip Call JavaScript