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?
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.
@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' : ''} />
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With