Sasha
Sasha

Reputation: 8705

XSL - add a value to attribute if value doesn't exist

When the element is created I need to change add value to data-id attribute (which is working), but once this value is set, I need to preserve it. The problem is that, if anything order is changed during creating the form, the id will be changed, and for data-id I need a fixed value. Any ideas.

I have this code for creating input element:

<div class="field" align="left">
    <xsl:element name="input">
    <xsl:attribute name="id"><xsl:value-of select="$field_id" /></xsl:attribute>
    <xsl:attribute name="name"><xsl:value-of select="$field_id" /></xsl:attribute>
    <xsl:attribute name="type">text</xsl:attribute>
    <xsl:attribute name="value"><xsl:value-of select="." /></xsl:attribute>
    <xsl:attribute name="maxlength"><xsl:value-of select="@maxlength" /></xsl:attribute>
    <xsl:attribute name="minlength"><xsl:value-of select="@minlength" /></xsl:attribute>
    <xsl:attribute name="class">text</xsl:attribute>
    <xsl:attribute name="data-id">
        <xsl:value-of select="$field_id" />
    </xsl:attribute>

    <xsl:attribute name="required">
    <xsl:choose>
        <xsl:when test="@required='required'">required</xsl:when>
                                                <xsl:otherwise>false</xsl:otherwise>
    </xsl:choose>
    </xsl:attribute>

    <xsl:attribute name="onchange">
                                            fieldPropertyChange('smalltext', '<xsl:value-of select="$field_id" />');
    </xsl:attribute>
</xsl:element>

Upvotes: 0

Views: 564

Answers (1)

Tomalak
Tomalak

Reputation: 338396

In HTML, the opposite of reqired="required" is not required="false". Read the spec on boolean attributes.

The values "true" and "false" are not allowed on boolean attributes. To represent a false value, the attribute has to be omitted altogether.

Just leave out the "required" attribute if a field is optional.

Additionally you are missing attribute value templates. <xsl:attribute> is not often needed in general and not at all in your sample. The same goes for <xsl:element>.

Here is what your code should look like.

<div class="field" align="left">
    <input
        id="{$field_id}" name="{$field_id}" type="text" class="text" 
        value="{.}" data-id="{$field_id}"
        onchange="fieldPropertyChange('smalltext', '{$field_id}')"
    >
        <xsl:copy-of select="@maxlength|@minlength|@required[. = 'required']" />
    </input>
</div>

You want an <input> with a bunch of attributes. And you want to copy the attributes @maxlength, @minlength (if they exist in the source) and @required (but only if it actually has a value of 'required' in the source).

<xsl:copy-of> is the right choice for such a situation.

On a further note, you might want to get rid of onchange. I recommend you use jQuery and a separate script file for event handling and keep all Javascript out of your HTML code.

Upvotes: 1

Related Questions