Skip to main content

Disabling HTML elements (in JSPs) with JSTL's "c:if"

I've been doing some Spring-based web forms work recently and one area of interest was around disabling certain input fields until particular values were set in the form-backing object. I wanted to ensure that particular radio buttons were disabled if the value was not what I expected.

Below is a statically disabled Spring radiobutton:
<form:radiobutton path="name" disabled="true"/>
For example's sake, I wanted to disabled the button if the name field of the form-backing object was "beacock", so what I needed was a boolean variable which captured the output of my particular test:
<c:if test=" eq 'beacock'">
<c:set var="isMe" value="true"/>
I could then use the above isMe variable in the following:
<form:radiobutton path="name" disabled="${isMe}"/>
Simple huh? But you can go a step further in the strive for clean code, the tag can take an optional var parameter which is a holder for the outcome of the boolean expression:
<c:if test="${ eq 'beacock'}" var="isMe"/>
So now the whole thing becomes:
<c:if test="${ eq 'beacock'}" var="isMe"/>
<form:radiobutton path="name" disabled="${isMe}"/>
Although you can perform complex expressions in the ${} tags, you can use the ternary operator:
value="${isMe ? 'Andrew Beacock' : 'Someone Else'}"
Here are a few more things I've found you can use as well:
${not isMe}
${not isMe or someOtherVariable}
A very good reference for all things JSTL is the JSTL quick reference - an appendix of one of the Manning books. Also the TLD documentation of the Spring Form Tag library is full of all the optional stuff.

Technorati Tags: , , , ,


Anonymous said…
Nice Tip!
Unknown said…
thanks man you saved my day