【问题标题】:Select all checkbox in primefaces选中primefaces中的所有复选框
【发布时间】:2019-03-10 20:25:53
【问题描述】:

逻辑的要求是:
- 我有一个复选框列表(我使用 p:selectManyCheckbox)。
- 我还有一个复选框,如果它被选中,其他复选框也应该被选中(我为此使用 p:selectBooleanCheckbox)
- 让我举一个具体的例子,现在我有 3 个复选框:
+ 全选
+ 项目 1
+ 项目 2

如果选中“全选”,则选中“项目 1”和“项目 2”。如果未选中“全选”,则未选中“项目 1”和“项目 2”。
如果未选中“项目 1”或“项目 2”之一,则应取消选中“全选”。如果同时选中了“item 1”和“item 2”,则应自动选中“select all”。

为了实现这一点,我使用 javascript 处理每个复选框的 onchange 事件。
对于全选,onchange = updateOtherCheckboxes(otherCheckboxes, selectAllCheckbox)

function updateCheckboxes(otherCheckboxes, selectAllCheckbox) {
	otherCheckboxes.inputs.each(function() {
		if (selectAllCheckbox.isChecked()) {
			$(this).prop('checked', false);
		} else {
			$(this).prop('checked', true);
		}
		$(this).trigger('click');
	});
}

对于其他复选框,onchange = updateSelectAllCheckbox(otherCheckboxes, selectAllCheckbox)

function updateSelectAllCheckbox(otherCheckboxes, selectAllCheckbox) {
	var notAllCheckboxesChecked = false;
	otherCheckboxes.inputs.each(function() {
		if ($(this).is(':checked') == false) {
			notAllCheckboxesChecked = true;
			return false;
		}
	});
	if (notAllCheckboxesChecked && selectAllCheckbox.input.is(':checked') == true) {
		selectAllCheckbox.input.trigger('click');
	} else if (!notAllCheckboxesChecked && selectAllCheckbox.input.is(':checked') == false) {
		selectAllCheckbox.input.trigger('click');
	}
}

这里的问题是,在 updateCheckboxes() 函数中,会触发其他复选框的点击事件,并会调用 updateSelectAllCheckbox,但我不希望这样。那么如何防止在触发点击事件后在 updateCheckboxes() 函数中调用 updateSelectAllCheckbox() 函数。

【问题讨论】:

    标签: javascript checkbox primefaces selectmanycheckbox selectbooleancheckbox


    【解决方案1】:

    您不必调用$(this).trigger('check'),因为这将触发点击事件,您之前的代码$(this).prop('checked', true) 已经确保复选框将被选中,因此您不必再触发click 事件。

    如果$(this).prop('checked', true) 不起作用,您也可以尝试:$(this).attr('checked', true);

    【讨论】:

    • 嗨,斯文,我在没有触发器的情况下尝试过('click'),但在 UI 上没有选中/取消选中其他复选框
    • @nguyenbkcse 我用另一个建议更新了我的答案:)
    • 嗨,斯文,我也尝试了你的新解决方案,但它保持不变:(
    • 您能否在答案中提供一个实时工作示例或使用工作代码的 codepen 链接?所以我可以尝试一些事情:)
    • 抱歉,我现在无法在哪里为您提供我的实时代码,因为我使用的是 primefaces,而且似乎没有在线地方可以测试 primefaces 代码。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多