Skip to main content

By clicking Submit, you agree to the developerWorks terms of use.

The first time you sign into developerWorks, a profile is created for you. Select information in your profile (name, country/region, and company) is displayed to the public and will accompany any content you post. You may update your IBM account at any time.

All information submitted is secure.

  • Close [x]

The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerworks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

By clicking Submit, you agree to the developerWorks terms of use.

All information submitted is secure.

  • Close [x]

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
Also available in:   Chinese  Russian  Japanese

Activity:  14805 views
Comments:  

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).

Report abuse help

Report abuse

Thank you. This entry has been flagged for moderator attention.


Report abuse help

Report abuse

Report abuse submission failed. Please try again later.


developerWorks: Sign in


Need an IBM ID?
Forgot your IBM ID?


Forgot your password?
Change your password

By clicking Submit, you agree to the developerWorks terms of use.

 


The first time you sign into developerWorks, a profile is created for you. Select information in your profile (name, country/region, and company) is displayed to the public and will accompany any content you post. You may update your IBM account at any time.

Choose your display name

The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerWorks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

(Must be between 3 – 31 characters.)

By clicking Submit, you agree to the developerWorks terms of use.

 


Rate this article

Comments

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