使用 JavaScript 的 CheckBoxList 项目
我有一个包含几个项目和一个所有选项的清单。用户可以选择全部,我希望这会选中所有选项,如果他们取消选中所有选项,它将取消选中所有选项。
我用下面的代码完成了这一点。
<script language="javascript" type="text/javascript">
function CheckBoxListSelect(cbControl) //, state)
{
var chkBoxList = document.getElementById(cbControl);
var chkBoxCount= chkBoxList.getElementsByTagName("input");
alert(chkBoxCount[0].checked);
for(var i=0;i<chkBoxCount.length;i++)
{
chkBoxCount[i].checked = chkBoxCount[0].checked //state;
}
return false;
}
</script>
cblAffiliation.Attributes.Add("onclick", "javascript: CheckBoxListSelect ('" & cblAffiliation.ClientID & "');")
问题是,如果我选择任何一个框,它会循环遍历,然后将它们设置为所有选项。我无法找出解决此问题的最佳方法。
我想避免使用复选框列表旁边的复选框,然后我必须使其与复选框列表对齐。
I have a checkoxlist with a couple of items and an all option. The user can select all and I want this to check off all the options and if they uncheck all it will uncheck all options.
I have accomplished this with the following code.
<script language="javascript" type="text/javascript">
function CheckBoxListSelect(cbControl) //, state)
{
var chkBoxList = document.getElementById(cbControl);
var chkBoxCount= chkBoxList.getElementsByTagName("input");
alert(chkBoxCount[0].checked);
for(var i=0;i<chkBoxCount.length;i++)
{
chkBoxCount[i].checked = chkBoxCount[0].checked //state;
}
return false;
}
</script>
cblAffiliation.Attributes.Add("onclick", "javascript: CheckBoxListSelect ('" & cblAffiliation.ClientID & "');")
The issue is that if I select any of the boxes it loops through and then sets them to whatever the all option is. I am having trouble figuring out the best way to get around this.
I want to avoid using a checkbox next to the checkboxlist, then I have to make that line up with the checkboxlist.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
只需检查单击的框是否为全部选项。如果是,那就继续更换其余的盒子。如果不是,请检查所有选项以查看是否全部选中,以便您可以更新“全部”复选框。
编辑
您可能想要使用 onChange,而不是 onClick,onClick 可能会在给定复选框上的值更改之前被调用。
代码未检查,请原谅语法问题。
Simply check to see if the box clicked was the all option. If it was, then go ahead and change the rest of the boxes. If it isn't, then check all the options to see if they are all checked so you can update the 'All' checkbox.
EDIT
You might want to use onChange, instead of onClick, onClick will probably be called before the value on the given checkbox is changed.
Code not checked, please forgive syntax problems.
我认为这段代码会对您有所帮助。
I think this code will help you.