Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditionally set an attribute on an element with JSP Documents (JSPX)

In HTML forms, buttons can be disabled by defining the "disabled" attribute on them, with any value:

<button name="btn1" disabled="disabled">Hello</button>

If a button is to be enabled, the attribute should not exist as there is no defined value that the disabled attribute can be set to that would leave the button enabled.

This is causing me problems when I want to enable / disable buttons when using JSP Documents (jspx). As JSP documents have to be well-formed XML documents, I can't see any way of conditionally including this attribute, as something like the following isn't legal:

<button name="btn1" <%= (isDisabled) ? "disabled" : "" %/> >Hello</button>

While I could replicate the tag twice using a JSTL if tag to get the desired effect, in my specific case I have over 15 attributes declared on the button (lots of javascript event handler attributes for AJAX) so duplicating the tag is going to make the JSP very messy.

How can I solve this problem, without sacrificing the readability of the JSP? Are there any custom tags that can add attributes to the parent by manipulating the output DOM?

like image 225
iainmcgin Avatar asked Oct 01 '08 10:10

iainmcgin


Video Answer


2 Answers

I use a custom JSP tag with dynamic attributes. You use it like this:

<util:element elementName="button" name="btn1" disabled="$(isDisabled ? 'disabled' : '')"/>

Basically, what this tag does is generate an XML element with elementName and puts all attributes present in the tag, but skips the empty ones.

The tag itself is pretty easy to implement, my implementation is just 44 lines long.

like image 120
alex Avatar answered Sep 22 '22 14:09

alex


@alex great solution to use the ternary operator. I add some of my example, that thanks to you, I just changed the result of the condition, if true, writes the attribute, otherwise not write anything

to populate the list and select the value used, avoiding c:if

<select id="selectLang" name="selectLang" >
<c:forEach var="language" items="${alLanguages}" >
    <option value="${language.id}" ${language.code == usedLanguage ? 'selected' : ''} >${language.description}</option>
</c:forEach>

to check at start a radio button to avoiding c:if:

<input type="radio" id="id0" value="0" name="radio" ${modelVar == 0 ? 'checked' : ''} />
<input type="radio" id="id1" value="1" name="radio" ${modelVar == 1 ? 'checked' : ''} />
<input type="radio" id="id2" value="2" name="radio" ${modelVar == 2 ? 'checked' : ''} />
like image 37
pagurix Avatar answered Sep 21 '22 14:09

pagurix