在JSP中选择All Check Boxes

时间:2013-09-30 11:03:36

标签: html forms jsp if-statement checkbox

我希望能够选中所有复选框或按钮,这样就可以设置要检查的所有其他复选框的值。无论如何在jsp中实现这一点?我在考虑这样的事情:

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

我知道条件有效,因为我已经使用过了,但我如何设置一个复选框来检查if语句。

1 个答案:

答案 0 :(得分:2)

似乎你错过了JSP只是一个HTML代码生成器的事实。

在HTML中,选中的复选框由checked属性的存在表示。

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

您在JSP中需要做的就是它可以生成所需的HTML输出。

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

或者,如果您不想复制已检查和未检查状态的整个HTML,但只想生成所需的属性:

<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"' : ''} />
...

或者,如果您实际拥有某些集合中的值,您可以使用<c:forEach>进行迭代,而您不想为每个值复制所有HTML输入元素,那么请执行以下操作:

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

当最终用户禁用JS时,无需笨拙的JS黑客攻击/解决方法,无论如何都会失败。

相关问题