I am trying to assign a random number generated by javascript function to a xsl variable which will be used to construct a query string for redirect purpose. Example of code:

<xsl:variable name ="tstVar1" select ="1" />
<xsl:variable name="tstVar" select="null" />

<script type="text/javascript">
var a ='<xsl:value-of select="$tstVar1"/>';
var b = Math.floor(Math.random() * (100 - 50 + a)) + a;

I need to assign the value of b to tstVar. How can i do this ?


1 Answer 1


If this is XSLT code running natively in the browser, then the XSLT code is executed to generate an HTML page which in this case contains a script element which contains some Javascript. That Javascript doesn't exist until the XSLT has finished executing, so clearly it can't be executed until it exists.

If you want a more dynamic execution model, consider Saxon-JS. This has much more flexibility for calling backwards and forwards between XSLT and JS code, and it also supports XSLT 3.0 / XPath 3.1 rather than only 1.0.

(I was going to say that because it supports XPath 3.1, you don't actually need to call out to Javascript to get a random number - XPath 3.1 has a random number generator function built in - but unfortunately that's part of the "higher order function" option which Saxon-JS doesn't yet implement).

Not the answer you're looking for? Browse other questions tagged or ask your own question.