iCeR
iCeR

Reputation: 149

How Can I Add The Existing onclick attribute ?(xslt)

XML:

<CONTROLS>
        <BUTTON>
               <input name="myButton" onclick="existingFunction();"/>
        </BUTTON>
        <LABEL>
               Text ME
        </LABEL>

</CONTROLS>

XSLT:

    <xsl:template match="/">
       <xsl:apply-templates select="CONTROLS/BUTTON/input"/>
    </xsl:template>  

    <xsl:template match="input">
        <xsl:variable name="existingOnclickFunction" select="/@onclick"/>
        <xsl:copy>
          <xsl:attribute name="onclick">
             <xsl:value-ofselect="$existingOnclickFunction"/>newFunction();
           </xsl:attribute>
          <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
       </xsl:template>

   <!--Identity template copies content forward -->
      <xsl:template match="@*|node()">
        <xsl:copy>
          <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
      </xsl:template>

Expected Output:

<input name="myButton" onclick="existingFunction();newFunction(); "/>

QUESTION:

 I'm getting the "input" node using xpath/template and adding another function on the 

"onclick" attribute. Is it possible? If yes, am I missing something here? My code doesn't work. Is there another approach?

 Thanks in advance :)

Upvotes: 0

Views: 5001

Answers (1)

Dimitre Novatchev
Dimitre Novatchev

Reputation: 243469

This transformation:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>

 <xsl:template match="input">
   <input onclick="{@onclick}newFunction();">
      <xsl:copy-of select="@*[not(name()='onclick')]"/>
   </input>
 </xsl:template>
 <xsl:template match="text()"/>
</xsl:stylesheet>

when applied on the provided XML document:

<CONTROLS>
    <BUTTON>
        <input name="myButton" onclick="existingFunction();"/>
    </BUTTON>
    <LABEL>Text ME</LABEL>
</CONTROLS>

produces the wanted, correct result:

<input onclick="existingFunction();newFunction();" name="myButton"/>

Explanation:

Proper use of templates and of AVT (Attribute Value Templates).

Upvotes: 1

Related Questions