如何设置单个复选框来切换/取消切换其他复选框
How to setup a single checkbox to toggle / untoggle other check boxes?
设置一个对话框(包含两个div):
(1)一个标签,它包含一个单独的复选框,标记为Select All。
<div class="div01">
<div class="notRequiredPrefix"></div>
<input type="checkbox"
name="root.module.emailCheckBox"
id="selectAllEmailsId"
onclick="selectAllEmails(this)"/>
<label for="selectAllEmailsId">Select All</label>
<div class="notRequiredSuffix"></div>
</div>
</div>
(2)包含对一堆复选框(包含电子邮件地址)的引用的A。
<div id="emailCheckListId" class="checkList">
<ul id="emailCheckListId_ul">
<li>
<label for="root.module.emailCheckList_0" class="checkListLabel">
<input type="checkbox"
value="johndoe@aol.com"
id="root.module.emailCheckList_0"
name="root.module.emailCheckList"/>
johndoe@aol.com
</label>
</li>
<li>
<label for="root.module.emailCheckList_1" class="checkListLabel">
<input type="checkbox"
value="janedoe@aol.com"
id="root.module.emailCheckList_1"
name="root.module.emailCheckList"/>
janedoe@aol.com
</label>
</li>
</ul>
</div>
JavaScript代码:
function selectAllEmails(field) {
if (field.checked) {
// Declare array
var emails = [];
// Iterate through each array and put email addresses into array
$('#emailCheckListId_ul input:checkbox').each(function() {
alert($(this));
// Set all checkboxes to true and
// make them checked how to do that here?
emails.push($(this).val());
});
// Assign variable as To: text field by obtaining element's id.
var textField = document.getElementById("root.module.email");
// Add / Remove array from text field
textField.value = emails;
} else if (!field.checked){
// How to remove any possible check boxes that are checked
// and remove them from text field
}
}
实际情况是,当我点击Select All复选框时,它会用所有的电子邮件地址填充我的To:文本字段。
但是,属于emailCheckListId_ul中的复选框被选中。
如何设置它,以便如果我单击Select All,则填充所有复选框,当我取消选中Select All时,将从复选框中删除所有复选框,并从To:文本字段中删除电子邮件地址?
感谢您花时间阅读这篇文章
要选中复选框,请将其checked属性设置为true:
this.checked = true;
使用
可以更有效地收集值:emails.push(this.value);
更一般地说,如果您首先将每个复选框的状态设置为selectAllEmails复选框的状态,则可以设置复选框的已选中状态:
this.checked = selectAllEmails.checked;
然后根据检查的邮件设置电子邮件数组的值。
逻辑有点复杂,因为您想:
- 如果"全选"复选框被选中并被选中,则选中所有复选框,并(可能)将标签更改为"取消选中所有"
- 如果任何邮件地址复选框未选中,则必须选中"select all"复选框并将标签设置为"select all"。
- 如果单击"select all"复选框,则取消选中所有复选框,结果是未选中。
因此,您需要一个函数来处理单击,另一个函数来根据单击完成时选择的复选框来整理电子邮件地址。
相关文章:
- 如何使用javascript检测数据表分页的其他页面中的复选框
- 在其他文本输入字段中输入文本时启用复选框
- 选中一个复选框后,使用html.checkbox自动禁用其他复选框
- 当选中一个复选框时,表单中的所有其他复选框都必须禁用-不工作
- 具有延迟的多个复选框选择以检查其他复选框更改
- Javascript错误,根据其他复选框的结果更新复选框/按钮
- 如果选中了其他复选框,则取消选中复选框
- 使用JavaScript获取widgetVar或选中/取消选中所有其他PrimeFaces复选框
- 仅从表中选中所有复选框,而不从其他表中选中所有复选框
- 复选框在选中时触发函数,如果未选中,则触发其他函数
- 选中后选中所有其他复选框
- 取消选中复选框将取消选中表中的其他复选框
- jQuery - 选中所有/取消选中所有复选框 - 然后取消选中(或选中)其他复选框
- 复选框状态和其他属性
- Jquery如果选中某个复选框,则禁用其他复选框
- 翡翠,如果其他速记选择复选框
- 复选框启用 Onload 以显示其他元素
- 单击具有类似类的复选框时,禁用其他复选框
- 如何在jsp中插入单选按钮、复选框和其他输入类型
- Javascript/JQuery设置复选框的值,同时禁用其他复选框