[英]How do I check all checkboxes on an HTML page with one click (Array of checkboxes)
I have the following HTML: 我有以下HTML:
<form name="smform" id="smform" method="post" action="">
<input type="checkbox" name="Check_All" onClick="Check(document.smform.check)" >
<input type="checkbox" name="check" value="blue_color"> Blue<br>
<input type="checkbox" name="check" value="green_color"> Green<br>
<input type="checkbox" name="check" value="orange_color"> Orange<br>
</form>
With the this JS: 使用此JS:
function Check(chk)
{
if(document.smform.Check_All.checked){
for (i = 0; i < chk.length; i++)
chk[i].checked = true ;
document.smform.Check_All.checked = true;
}else{
for (i = 0; i < chk.length; i++)
chk[i].checked = false ;
document.smform.Check_All.checked = false;
}
}
And this this is working fine, I can select or deselect all checkboxes, but in order to post this as an ARRAY, my check boxes will have the name="check[]"
like: 这可以正常工作,我可以选择或取消选中所有复选框,但是为了将其发布为ARRAY,我的复选框将具有name="check[]"
例如:
<input type="checkbox" name="check[]" value="blue_color"> Blue<br>
<input type="checkbox" name="check[]" value="green_color"> Green<br>
<input type="checkbox" name="check[]" value="orange_color"> Orange<br>
But in this case my JS is not working. 但是在这种情况下,我的JS无法正常工作。 How can I adapt this JS so it works with name="check[]"
? 我如何适应此JS,使其与name="check[]"
?
All help is appreciated. 感谢所有帮助。
Just dont use dot-notation, instead use square brackets and a string: 只是不要使用点符号,而是使用方括号和字符串:
onClick="Check(document.smform['check[]'])"
Live example: http://jsfiddle.net/5JCMS/ 实时示例: http : //jsfiddle.net/5JCMS/
you can use getElementsByTagName
to get all checkboxes 您可以使用getElementsByTagName
来获取所有复选框
var inputs = document.getElementsByTagName("input");
Check(inputs);
function Check(chk)
{
if(document.smform.Check_All.checked){
for (i = 0; i < chk.length; i++){
if(inputs[i].type == "checkbox"){
chk[i].checked = true ;
}
}
document.smform.Check_All.checked = true;
}else{
for (i = 0; i < chk.length; i++){
if(inputs[i].type == "checkbox"){
chk[i].checked = false ;
}
}
document.smform.Check_All.checked = false;
}
}
Use Jquery. 使用Jquery。 You can add a class to all the checkboxes you wish to check 您可以将类别添加到所有要检查的复选框
<input type='checkbox' class='autocheckable someOtherClass' />Blue
And then do as described here: Setting "checked" for a checkbox with jQuery? 然后按照此处所述执行操作: 使用jQuery将复选框设置为“已选中”?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.