XSLT and jQuery Samples

I have been doing a lot of of XSLT and jQuery and thought I’d share a few snippets that others may find useful in future.

Example 1: Emit simple JavaScript / jQuery in XSLT:

<xsl:template match="something" xml:space="preserve">

  <!– Blank out the query friendly filters hidden field –>
  <script type="text/javascript">
    $(document).ready(function(){
      $("#QueryFriendlyFilters").val("empty");
    });
  </script>

</xsl:template>

That bit emits some JavaScript that waits for the page to finish loading (because of the $(document).ready(…)) and then sets the value of a hidden field named QueryFriendlyFilters to the literal value “empty”.

Example 2: Use <xsl:if> to check “greater than”,  “less than”, etc.

<xsl:template match="something" xml:space="preserve">

  <div id="fdcAllFilters">
 
    <xsl:if test="@Count>0">
      <span class="fdcFilterLabel">Current filters:</span>
    </xsl:if>

    <!– more stuff happens here. –>

</xsl:template>

The above snippet checks to see if an attribute named “Count” of the “something” element is greater than zero.  The XML behind this would be something like:”

<something Count=”5” />

Example 3: Iterate through all elements, interspersing jQuery calls.

<!– Iterate through all the filters and display the correct  links. –>
<xsl:for-each select="UserFilter">

  <a class="FilterHref" href="javascript:mySubmitPage(‘RemoveUserFilter’,'{@ID}’)">[X]</a>

  <span class="fdcFilterLabel"><xsl:value-of select="@FilterValue"/></span>

  <script type="text/javascript">

    $(document).ready(function(){
        <xsl:text><![CDATA[$("#QueryFriendlyFilters").val( ($("#QueryFriendlyFilters").val() + " ]]></xsl:text>\"<xsl:value-of select="@FilterValue"/>\"<xsl:text><![CDATA["));]]></xsl:text>
    });

  </script>

</xsl:for-each>

The above snippet is the most complex and there may be easier ways to do it.

The XML behind this looks roughly like this:

<UserFilter ID=”123” FilterValue=”xyzzy” />

This snippet is iterating through <UserFilter> nodes. 

It first emits an anchor tag that when clicked invokes a JavaScript function that is already on the page, “mySubmitPage” and passes the value of an attribute on the <UserFilter> node named “ID”. 

It then emits some jQuery that waits for the page to load.  That jQuery updates a hidden field named “QueryFriendlyFilters” by adding the value of the FilterValue attribute.  Note all the crazy <xsl:text> and <![CDATA[ … ]]> stuff.

That’s it, hope it helps!

</end>

Subscribe to my blog.

Follow me on Twitter at http://www.twitter.com/pagalvin

2 thoughts on “XSLT and jQuery Samples

    1. Paul Galvin Post author

      Hi, sorry I never responded to this. It’s ancient at this point and so I won’t try. I hope you figured out what you were trying to do :).

      Reply

Leave a Reply

Your email address will not be published. Required fields are marked *