我有一个带有多个复选框的HTML页面。
我需要一个名称为“全选”的复选框。当我选择此复选框时,HTML页面中的所有复选框都必须被选中。我该怎么做呢?
我有一个带有多个复选框的HTML页面。
我需要一个名称为“全选”的复选框。当我选择此复选框时,HTML页面中的所有复选框都必须被选中。我该怎么做呢?
当前回答
JavaScript是最好的选择。下面的链接给出了一个使用按钮取消/全选的例子。你可以尝试调整它来使用复选框,只需使用你的“全选”复选框的onClick属性。
Javascript函数来检查或取消所有复选框
本页有一个更简单的示例
http://www.htmlcodetutorial.com/forms/_INPUT_onClick.html
其他回答
这个示例使用本地JavaScript,其中复选框变量名不同,即不全是“foo”。
<!DOCTYPE html>
<html>
<body>
<p>Toggling checkboxes</p>
<script>
function getcheckboxes() {
var node_list = document.getElementsByTagName('input');
var checkboxes = [];
for (var i = 0; i < node_list.length; i++)
{
var node = node_list[i];
if (node.getAttribute('type') == 'checkbox')
{
checkboxes.push(node);
}
}
return checkboxes;
}
function toggle(source) {
checkboxes = getcheckboxes();
for (var i = 0 n = checkboxes.length; i < n; i++)
{
checkboxes[i].checked = source.checked;
}
}
</script>
<input type="checkbox" name="foo1" value="bar1"> Bar 1<br/>
<input type="checkbox" name="foo2" value="bar2"> Bar 2<br/>
<input type="checkbox" name="foo3" value="bar3"> Bar 3<br/>
<input type="checkbox" name="foo4" value="bar4"> Bar 4<br/>
<input type="checkbox" onClick="toggle(this)" /> Toggle All<br/>
</body>
</html>
$(document).ready(function() {
$(document).on(' change', 'input[name="check_all"]', function() {
$('.cb').prop("checked", this.checked);
});
});
我不确定有人没有这样回答(使用jQuery):
$( '#container .toggle-button' ).click( function () {
$( '#container input[type="checkbox"]' ).prop('checked', this.checked)
})
它是干净的,没有循环或if/else子句,工作就像一个魅力。
<asp:CheckBox ID="CheckBox1" runat="server" Text="Select All" onclick="checkAll(this);" />
<br />
<asp:CheckBoxList ID="CheckBoxList1" runat="server">
<asp:ListItem Value="Item 1">Item 1</asp:ListItem>
<asp:ListItem Value="Item 2">Item 2</asp:ListItem>
<asp:ListItem Value="Item 3">Item 3</asp:ListItem>
<asp:ListItem Value="Item 4">Item 4</asp:ListItem>
<asp:ListItem Value="Item 5">Item 5</asp:ListItem>
<asp:ListItem Value="Item 6">Item 6</asp:ListItem>
</asp:CheckBoxList>
<script type="text/javascript">
function checkAll(obj1) {
var checkboxCollection = document.getElementById('<%=CheckBoxList1.ClientID %>').getElementsByTagName('input');
for (var i = 0; i < checkboxCollection.length; i++) {
if (checkboxCollection[i].type.toString().toLowerCase() == "checkbox") {
checkboxCollection[i].checked = obj1.checked;
}
}
}
</script>
这样就可以完成工作了:
$(':checkbox').each(function() {
this.checked = true;
});