Search code examples
javascriptxformsxsltforms

Call javascript from XForms action


I am experimenting with XForms and trying to dynamically load javascript, but cannot figure it out.

I am presenting a simple example - that is just an input field and button that loads the javascript:

<html xmlns="http://www.w3.org/1999/xhtml" xmlns:xf="http://www.w3.org/2002/xforms"
   xmlns:ev="http://www.w3.org/2001/xml-events" >
   <head>
      <title>Hello World in XForms</title>
      <xf:model>
         <xf:instance xmlns="">
            <data>
               <firstName/>
            </data>
         </xf:instance>
      </xf:model>

      <script type="text/javascript">
         var myFunction = function(){
           var name = document.getElementById("firstName").value;
           alert("Hello " + name + "!");
         }
      </script>
   </head>
   <body>
      <xf:label>Please enter your first name: </xf:label>
      <xf:input ref="firstName" id="firstName">         
      </xf:input>
      <br />
      <xf:trigger>
         <xf:label>Click me!</xf:label>
         <xf:action ev:event="DOMActivate">
            <xf:load resource="javascript:myFunction()" />
         </xf:action>
      </xf:trigger>
   </body>
</html>

So in my script I am trying to get the value from the input box and then show an alert box with concatenated string. Currently, I get "Hello undefined!"

Do you have an idea how to get the value from the firstName xf:input with Javascript? I know how to do it with XForms only, but this is sort of a proof of concept.

On a side note - I am using XSLTForms, so the XForms runs on the client.

Another hint might be in the fact that XSLTForms transforms the xf:input into several nested span elements with a <input type="text"> element, but that input element does not have a name or id.


Solution

  • With XSLTForms, there are different possibilities...

    If you want to access the value of the corresponding HTML input, I would suggest document.getElementById("firstName").xfElement.input.value.

    You could also use the node property to get the value stored in the bound node.

    Don't hesitate to browse DOM with a debugger to find how to get things from XSLTForms!

    --Alain