选择和取消选择带有单个复选框的复选框列表 [英] Select and unselect list of checkboxes with single checkbox

查看:103
本文介绍了选择和取消选择带有单个复选框的复选框列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两种复选框.一个是简单的复选框,例如t:selectBooleanCheckbox,另一个是动态生成的t:selectBooleanCheckbox列表.我想使用单个复选框来控制此列表.例如.选中或取消选中该列表时,也应对列表进行类似的操作.

I have two kinds of check boxes. One is a simple check box e.g t:selectBooleanCheckbox and another is a dynamically generated list of t:selectBooleanCheckbox. I want to control this list with the single check box. E.g. when it is selected or deselected, similar action should take place for the list as well.

推荐答案

使用JSF 1.x,有两种方法可以实现此目的.

With JSF 1.x there are two ways to achieve this.

  1. 单击复选框将表单提交给服务器.

  1. Submit the form to the server onclick of the checkbox.

<t:selectBooleanCheckbox value="#{bean.selectAll}" onclick="submit()" />

然后执行逻辑来选择/取消选择所有复选框.

And just do the logic to select/unselect all checkboxes.

public void submit() {
    for (CheckboxItem item : checkboxItems) {
        item.setSelected(selectAll);
    }
}

注意事项:对用户和开发人员不友好.用户看到内容闪烁,可能需要等待一段时间才能返回页面.开发人员必须保留所有相同形式的输入,并麻烦进行JSF验证(如果有).

Caveat: not user and developer friendly. User sees flash of content and might have to wait some time before page returns. Developer has to retain all inputs of the same form and hassle with JSF validation, if any.

使用JavaScript完全在客户端进行操作.

Use JavaScript to do the magic entirely at the client side.

<t:selectBooleanCheckbox value="#{bean.selectAll}" onclick="selectAll(this)" />

使用

function selectAll(checkbox) {
    var elements = checkbox.form.elements;
    for (var i = 0; i < elements.length; i++) {
        var element = elements[i];
        if (/checkboxId$/.test(element.id)) {
            element.checked = checkbox.checked;
        }
    }
}

但是,这假定动态列表生成的所有复选框元素的ID以checkboxId结尾.只需检查生成的HTML源即可发现模式.您至少知道现在应该朝哪个方向看.

This however assumes that all checkbox elements generated by your dynamic list have an ID ending with checkboxId. Just check the generated HTML source to spot the pattern. You at least know in which direction you should look now.

哦,别忘了编写类似的逻辑以在未选中列表中的复选框之一时取消选中全选"复选框.

Oh, don't forget to write similar logic to unselect the "select all" checkbox whenever one of the checkboxes in the list is unchecked.

对于JSF 2.x,您当然会使用<f:ajax>而不是onclick.

With JSF 2.x, you'd of course use <f:ajax> instead of onclick.

这篇关于选择和取消选择带有单个复选框的复选框列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆