Re: [xsl] Plse Help! something to do with counter....

Subject: Re: [xsl] Plse Help! something to do with counter....
From: Jeni Tennison <mail@xxxxxxxxxxxxxxxx>
Date: Mon, 30 Apr 2001 09:21:51 +0100
Hi Justin,

> Hi, I'm trying to create a form with checkboxes using XSLT, with
> each checkbox a different name, like "c1", "c2" util the last. a
> checkbox will be assign to each item in the XML.
> Is there a way to make a auto-increment counter and use it in the
> following tag?
> <input type="checkbox" name="XXX" value="{Index}">

The easiest thing is if you have nodes in your source XML that
represent the checkboxes that you want to create.  If you do, then you
can apply templates to those nodes, and use their position() to
generate the number, or even use xsl:number if you feel like it.  So
for example, if each of the checkboxes were represented by a checkbox
element in your source XML, you could apply templates to them:

  <xsl:apply-templates select="checkbox" />

Then have a template that creates the input element when it's applied
to a checkbox element:

<xsl:template match="checkbox">
   <input type="checkbox" name="XXX" value="c{position()}" />

If you only have the number of checkboxes you want, and not nodes to
represent them, then you can use either a recursive template or the
Piez Method for iterating a set number of times.

Using recursion, you have a template that takes two parameters: a
count and a maximum.  Within the template, you emit the input element
you want, based on the $count parameter, and then, if the count is
less than the maximum, call the template again:

<xsl:template name="checkboxes">
   <xsl:param name="count" select="1" />
   <xsl:param name="max" select="1" />
   <input type="checkbox" name="XXX" value="c{$count}" />
   <xsl:if test="$count &lt; $max">
      <xsl:call-template name="checkboxes">
         <xsl:with-param name="count" select="$count + 1" />
         <xsl:with-param name="max" select="$max" />

You call this template initially by setting the $max parameter to the
number of checkboxes you need:

  <xsl:call-template name="checkboxes">
     <xsl:with-param name="max" select="$num-checkboxes" />

Using the Piez Method, you get a set of random nodes, which has to be
at least as big as the largest number of checkboxes you'll ever need.
You then select from that node set a number of nodes equal to the
number of checkboxes that you want.  Then you iterate over that set of
nodes, giving a checkbox for each.  Within the loop, you can use
position() to give you an incrementing count:

  <xsl:variable name="random-nodes" select="document('')//node()" />
  <xsl:for-each select="$random-nodes[position() &lt;= $num-checkboxes]">
     <input type="checkbox" name="XXX" value="c{position()}" />
I hope that helps,


Jeni Tennison

 XSL-List info and archive:

Current Thread