Clientside onLoad events on Xpages

I wanted to set the focus (client side) on an input field in my Xpage. This required:
  • adding a function to the onLoad event
  • referencing the (generated) id of my editable field: in the Xpage the element is named “userName”.

As I found out, there are a couple of ways to add clientside javascript to your Xpage (the dojo.addOnLoad function I’m using defers execution of the code until all HTML is loaded, so it doesn’t matter where you place your code):

  • Add the code directly to the XPage source:
    <script type="text/javascript">
    dojo.addOnLoad( function() {
     alert("added directly in source");
    } );
    </script>
  • Add a Computed Field to your Xpage, set its Content type to “HTML” and enter a value that evaluates to a string, including the <script> tags:
    "<script type="text/javascript">" +
    "dojo.addOnLoad( function() {" +
    " alert("computed field");"
    "} );"
    "</script>"

    The value if the computed field is computed on the server, so if I want to get the generated ID of the Editable field, I have to use the getClientId() function:

    "<script type="text/javascript">" +
    "dojo.addOnLoad( function() {" +
    " alert("The id of the element is: " + getClientId("userName") + "");" +
    "} );" +
    "</script>"
  • Add an “Output script” core control to the Xpage and edit its value. This control is rendered in the browser with <script></script> tags (if “Output script” isn’t available in the menu you have to enable it in the Designer preferences through File – Preferences – Domino Designer – Palette – Core Controls):
    dojo.addOnLoad( function() {
        alert("Output script control");
    } );

    The value of the Output script is passed to the browser as clientside Javascript, but is first evaluated by the server. So if I wanted to reference a clientside document ID, I’d have to use the “#{id:userName}” syntax:

    dojo.addOnLoad( function() {
        var id = "#{id:userName}";
        alert("The id of the element is: " + id);
    } );

Since the first method didn’t allow me to reference the generated ID of the Editable field and the second method required me to escape and wrap everything in quotes I went with the third method. The final code in the Output script element is now:

dojo.addOnLoad( function() {
 var objFocus = dojo.byId("#{id:userName}");
 if (objFocus) {
   if (!objFocus.disabled &amp;&amp; objFocus != "hidden") {
     objFocus.focus();
   }
 }
 } );

To set the focus only if a new document is being edited, I’ve added the following formula to the “rendered” property of the Output script control:

currentDocument.isEditable() &amp;&amp; currentDocument.isNewNote();