Skip to main content

XForms tip: Call JavaScript from an XForms form

Nicholas Chase (ibmquestions@nicholaschase.com), Freelance writer, Backstop Media
Nicholas Chase has been involved in Web site development for companies such as Lucent Technologies, Sun Microsystems, Oracle, and the Tampa Bay Buccaneers. Nick has been a high school physics teacher, a low-level radioactive waste facility manager, an online science fiction magazine editor, a multimedia engineer, an Oracle instructor, and the Chief Technology Officer of an interactive communications company. He is the author of several books, including XML Primer Plus (Sams).

Summary:  Because XForms controls are part of a namespace separate from the HTML and page, you cannot use the usual methods for calling JavaScript™ in response to user events, such as the onclick handler. So what are you to do if you need to call JavaScript from an XForms form? This tip shows you how to do it.

View more content in this series

Date:  09 Jan 2007
Level:  Intermediate
Activity:  2950 views

Before you begin: Notes about this tip

This tip is specific to a particular task. For background information on XForms, see the three-part series Introduction to XForms.

The XForms samples described in this tip have been tested and work with Firefox 1.5 (with the XForms extension installed) and Microsoft® Internet Explorer 6 with the Formsplayer control installed. The download contains the XHTML file for Firefox and the HTML file for IE.


The basic form

XForms provides an easy way to add interactivity to a form by using triggers and actions, but in most cases, those actions are XForms-related actions. In this tip, you are going to build a form that includes a button that executes JavaScript when clicked. Let's start with the basic form (Listing 1).


Listing 1. The basic form

<?xml version="1.0" encoding="ASCII"?>
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:ev="http://www.w3.org/2001/xml-events"
      xmlns:xforms="http://www.w3.org/2002/xforms">
  <head>
    <title>Instance Data-To-XHTML/XForms Example</title>

    <xforms:model id="auctionItems">
      <xforms:instance id="auctions" src="auctions.xml"/>
      <xforms:submission id="submit_model_auctionItems"
                         action="http://xformstest.org/cgi-bin/showinstance.sh"
                         method="post" instance="auctions"/>
    </xforms:model>
    <link href="gen_default.css" rel="stylesheet"/>
  </head>
  <body>
    
    <h1 align="center" id="myTest">Auction Item Inventory</h1>
    
    <xforms:repeat nodeset="instance('auctions')/auctionItem"
 id="repeatAuctionItems">
      <h2 align="center">Auction Item</h2>
      <xforms:input ref="@itemID">
        <xforms:label>Item ID</xforms:label>
      </xforms:input>
      <xforms:input ref="purchaseDate">
        <xforms:label>Purchase Date</xforms:label>
      </xforms:input>
      <xforms:input ref="auctionLength">
        <xforms:label>Auction Length</xforms:label>
      </xforms:input>
      <xforms:input ref="purchasePrice">
        <xforms:label>Purchase Price</xforms:label>
      </xforms:input>

      <xforms:input ref="description">
        <xforms:label>Description</xforms:label>
      </xforms:input>
      <xforms:input ref="estimatedValue">
        <xforms:label>Estimated Value</xforms:label>
      </xforms:input>
    </xforms:repeat>

    <xforms:group>

      <xforms:trigger>
        <xforms:label>Show action</xforms:label>
      </xforms:trigger>

      <xforms:trigger>
        <xforms:label>Insert Auction Item</xforms:label>
        <xforms:insert nodeset="instance('auctions')/auctionItem"
 at="index('repeatAuctionItems')"
                       position="after" ev:event="DOMActivate" />
      </xforms:trigger>
      <xforms:trigger>
        <xforms:label>Delete Auction Item</xforms:label>
        <xforms:delete nodeset="instance('auctions')/auctionItem"
 at="index('repeatAuctionItems')"
                       ev:event="DOMActivate" />
      </xforms:trigger>
    </xforms:group>

    <xforms:submit submission="submit_model_auctionItems">
      <xforms:label>Submit</xforms:label>
    </xforms:submit>

  </body>
</html>

The form includes a button that needs to show the action to which the form will be submitted, as you can see in Figure 1.


Figure 1. Form with Show action button
Form with Show action button

To do that, start by creating the actual script (Listing 2).


Listing 2. The JavaScript

...
  <head>
    <title>Instance Data-To-XHTML/XForms Example</title>

    <xforms:model id="auctionItems">
      <xforms:instance id="auctions" src="auctions.xml"/>
      <xforms:submission id="submit_model_auctionItems"
                         action="http://xformstest.org/cgi-bin/showinstance.sh"
                         method="post" instance="auctions"/>
    </xforms:model>
    <link href="gen_default.css" rel="stylesheet"/>

    <script type="text/javascript">
      var testJS= function()
                  {
                    alert('This form submits to: '+
                         document.getElementById('submit_model_auctionItems')
                                 .getAttribute('action'));
                  }            
    </script>

  </head>
  <body>
...

This script is JavaScript, but it interacts with the XForms form through standard DOM methods.

Now you need a way to call the script.


Loading a URL

The XForms load element is very similar to an HTML link, in that it tells the browser to load a resource, either in the existing window or in a new window. Fortunately, that means you can use it to call a URL. It's fortunate because you can reference this JavaScript as a URL. One way to handle this is to use the ref attribute to specify the resource to load. The problem here is that ref can only accept XPath expresions. That means you wind up with a structure like this (Listing 3).


Listing 3. The long way to load the JavaScript

<?xml version="1.0" encoding="ASCII"?>
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:ev="http://www.w3.org/2001/xml-events"
      xmlns:xforms="http://www.w3.org/2002/xforms">
  <head>
    <title>Instance Data-To-XHTML/XForms Example</title>

    <xforms:model id="auctionItems">
      <xforms:instance id="auctions" src="auctions.xml"/>
      <xforms:instance id="data">
        <data url="javascript:testJS()"/>
      </xforms:instance>
      <xforms:submission id="submit_model_auctionItems"
                         action="http://xformstest.org/cgi-bin/showinstance.sh"
                         method="post" instance="auctions"/>
    </xforms:model>
 ...
    </xforms:repeat>

    <xforms:group>

      <xforms:trigger>
        <xforms:label>Show action</xforms:label>
        <xforms:load ref="instance('data')/@url"
 ev:event="DOMActivate"/>
      </xforms:trigger>

      <xforms:trigger>
        <xforms:label>Insert Auction Item</xforms:label>
        <xforms:insert nodeset="instance('auctions')/auctionItem"
 at="index('repeatAuctionItems')"
                       position="after" ev:event="DOMActivate" />
      </xforms:trigger>
...

The XPath expression referenced by the load element points to a URL that refers to the script.

Fortunately, there's also an easier way to accomplish this. By using the resource attribute rather than ref, you can load the script directly (see Listing 4):


Listing 4. The short way to load the JavaScript

...
      <xforms:trigger>
        <xforms:label>Show action</xforms:label>
        <xforms:load resource="javascript:testJS()" ev:event="DOMActivate"/>
      </xforms:trigger>
...

In either case, clicking the button gives the desired result, as seen in Figure 2.


Figure 2. Clicking the button gives the desired result
Clicking the button gives the desired result

Summary

Using the load element, you can execute any URL. In order to do that, however, the URL must be contained in a data instance so that the load element's ref attribute contains an XPath expression. From there, the URL points to the actual JavaScript. Note also that that means you can execute any arbitrary JavaScript script that makes sense, even if it interacts with the XForms elements and attributes on the page.



Download

DescriptionNameSizeDownload method
Call JavaScript XForms samplescalljs_source.zip4KB HTTP

Information about download methods


Resources

Learn

  • Let Skimstone explain to you what XForms is.

  • See the Skimstone introduction to XForms.

  • To learn more about other possible schema types for your XForms inputs, check out w3cschools.

  • This series is a good guide for getting started using XForms.

  • Start here to learn about the Visual XForms Designer from alphaWorks.

  • In the XML area on developerWorks, get the resources you need to advance your skills in XForms and other XML technologies.

  • Browse the technology bookstore for books on these and other technical topics.

Get products and technologies

  • Get MozzIE, an open-source control that allows you to render XForms in IE.

Discuss

About the author

Nicholas Chase has been involved in Web site development for companies such as Lucent Technologies, Sun Microsystems, Oracle, and the Tampa Bay Buccaneers. Nick has been a high school physics teacher, a low-level radioactive waste facility manager, an online science fiction magazine editor, a multimedia engineer, an Oracle instructor, and the Chief Technology Officer of an interactive communications company. He is the author of several books, including XML Primer Plus (Sams).

Comments (Undergoing maintenance)



Trademarks  |  My developerWorks terms and conditions

Help: Update or add to My dW interests

What's this?

This little timesaver lets you update your My developerWorks profile with just one click! The general subject of this content (AIX and UNIX, Information Management, Lotus, Rational, Tivoli, WebSphere, Java, Linux, Open source, SOA and Web services, Web development, or XML) will be added to the interests section of your profile, if it's not there already. You only need to be logged in to My developerWorks.

And what's the point of adding your interests to your profile? That's how you find other users with the same interests as yours, and see what they're reading and contributing to the community. Your interests also help us recommend relevant developerWorks content to you.

View your My developerWorks profile

Return from help

Help: Remove from My dW interests

What's this?

Removing this interest does not alter your profile, but rather removes this piece of content from a list of all content for which you've indicated interest. In a future enhancement to My developerWorks, you'll be able to see a record of that content.

View your My developerWorks profile

Return from help

static.content.url=http://www.ibm.com/developerworks/js/artrating/
SITE_ID=1
Zone=XML
ArticleID=187351
ArticleTitle=XForms tip: Call JavaScript from an XForms form
publish-date=01092007
author1-email=ibmquestions@nicholaschase.com
author1-email-cc=dwxed@us.ibm.com

My developerWorks community

Tags

Help
Use the search field to find all types of content in My developerWorks with that tag.

Use the slider bar to see more or fewer tags.

Popular tags shows the top tags for this particular content zone (for example, Java technology, Linux, WebSphere).

My tags shows your tags for this particular content zone (for example, Java technology, Linux, WebSphere).

Use the search field to find all types of content in My developerWorks with that tag. Popular tags shows the top tags for this particular content zone (for example, Java technology, Linux, WebSphere). My tags shows your tags for this particular content zone (for example, Java technology, Linux, WebSphere).

Rate a product. Write a review.

Special offers