[英]Fire other checkboxes onclick() when main checkbox is selected/unselected
I have read many other question on SO regarding selecting all checkboxes, but couldn't find one that says how to trigger other checkboxes actions. 我已经阅读了关于选择所有复选框的许多其他问题,但是找不到表明如何触发其他复选框动作的问题。
I have a main checkbox, when this checkbox is selected all other checkboxes are selected as well. 我有一个主复选框,当选中此复选框时,还将选中所有其他复选框。 The thing is, other checkboxes have to perform their own action eg disable text fields .etc if they are checked/unchecked.
问题是,其他复选框必须执行自己的操作,例如,如果选中/取消选中,则禁用文本字段.etc。 I achieved this by adding onclick to each checkbox.
我通过向每个复选框添加onclick实现了这一点。 So how to call each checkbox onclick (or make each checkbox to perform their action) if the main checkbox is selected?
那么,如果选择了主复选框,那么如何调用每个复选框的onclick(或使每个复选框执行其操作)?
After reading about this I have made the following: 阅读此内容后,我做了以下工作:
// main checkbox functin that checks/unchecks other checkboxes.
function toggleAllCheckBoxes(source , operationType) {
checkboxes = document.getElementsByName("checkBox" + operationType);
for each(var checkbox in checkboxes)
checkbox.checked = source.checked;
// checkbox.addEventListener('click', true); // this is wrong.
}
//this will toggle text fields enabled/disabled
function toggleDisable(oldTable, newTable , checkBox)
{
if( document.getElementById(newTable) !=null)// in case to toggle only old table
{
document.getElementById(newTable).disabled = checkBox.checked;
}
document.getElementById(oldTable).disabled = checkBox.checked;
}
main checkbox: 主要复选框:
All<input type="checkbox" onClick="toggleAllCheckBoxes(this , '<?=$operationType?>')"/>
Other checkboxes 其他复选框
X<input name="checkbox" id="checkbox" onclick="toggleDisable('<?= $originalTableId?>' , '<?= $backupTableId?>' , this )" type="checkbox" />
So far this works fine, except, text fields are not being enabled/disabled if main checkbox is selected. 到目前为止,此方法工作正常,但如果选中了主复选框,则不会启用/禁用文本字段。 Although single checkboxes are able to do that.
尽管单个复选框能够做到这一点。
Thanks. 谢谢。
I see two issues: 我看到两个问题:
for each
operator in JavaScript. for each
运算符。 You'll need to use a normal for loop here. checked
attribute for the checkbox because, as you've seen, that will bypass all event handlers. checked
属性,因为如您所见,它将绕过所有事件处理程序。 Instead, call click()
on the checkbox and it will be checked (or unchecked) and all event handlers will be called. click()
,它将被选中(或取消选中),并将调用所有事件处理程序。 That will end up looking like this in toggleAllCheckBoxes
: 这样最终会在
toggleAllCheckBoxes
看起来像这样:
for(var i = 0; i < checkboxes.length; i++)
checkboxes[i].click();
Here's a Fiddle to try this code out on: http://jsfiddle.net/z4Ltc/ 这是一个小提琴手,可以尝试以下代码: http : //jsfiddle.net/z4Ltc/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.