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've just been struggling with the same problem. I tried using
<jsp:attribute name="disabled"/>
inside<c:if>
, but the compiler tries to attach the disabled attribute to thec:if
element which fails. But I found that this does work (stripes:submit
is an element for creating a button of type submit in stripes):It seems that
jsp:attribute
will not create an attribute at all if the body contains only whitespace, so you either getdisabled="disabled"
or nothing at all.This will only work if you are using some sort of taglib to generate the button, and the tag element must support the disabled attribute (passing it through to the underlying HTML element). You can't use
jsp:attribute
to add an attribute to a raw HTML element.You can use the
<jsp:text>
tag to solve this problem using valid XML:This is obviously more verbose than some other solutions. But it's completely self-contained: no custom tags required. Also, it scales easily to as many attributes as you need.
I use a custom JSP tag with dynamic attributes. You use it like this:
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.