Crouch
Crouch

Reputation: 896

Select All Check Boxes in JSP

I want to be able to have a select all check box or button either is fine which will then set the value of all other checkboxes to be checked. Is there anyway of achieving this in jsp? I was thinking of something like this:

<c:if test="${!empty param.selectall}">
    //set all others to checked
</c:if>

I know the condition works because I've already used it but how do i go about setting a checkboxes to checked inside an if statement.

Upvotes: 0

Views: 2907

Answers (1)

BalusC
BalusC

Reputation: 1108672

It seems that you somehow missed the fact that JSP is merely a HTML code generator.

In HTML, a checked checkbox is represented by the presence of the checked attribute.

<input type="checkbox" ... checked="checked" />

All you need to do in JSP is that it generates exactly the desired HTML output.

<c:if test="${not empty param.selectall}">
    <input type="checkbox" ... checked="checked" />
    <input type="checkbox" ... checked="checked" />
    <input type="checkbox" ... checked="checked" />
    ...
</c:if>

Or, if you'd rather not want to duplicate the whole HTML for checked and non-checked states, but just want to generate the desired attribute only:

<input type="checkbox" ... ${not empty param.selectall ? 'checked="checked"' : ''} />
<input type="checkbox" ... ${not empty param.selectall ? 'checked="checked"' : ''} />
<input type="checkbox" ... ${not empty param.selectall ? 'checked="checked"' : ''} />
...

Or, if you actually have the values in some collection which you could iterate over using <c:forEach> and you'd rather not want to duplicate all HTML input elements for every single value, then do:

<c:forEach items="${bean.availableItems}" var="availableItem">
    <input type="checkbox" ... value="${availableItem}" ${not empty param.selectall ? 'checked="checked"' : ''} />
</c:forEach>

No need for clumsy JS hacks/workarounds which would fail anyway when the enduser has JS disabled.

Upvotes: 2

Related Questions