我有一个带有多个复选框的HTML页面。
我需要一个名称为“全选”的复选框。当我选择此复选框时,HTML页面中的所有复选框都必须被选中。我该怎么做呢?
我有一个带有多个复选框的HTML页面。
我需要一个名称为“全选”的复选框。当我选择此复选框时,HTML页面中的所有复选框都必须被选中。我该怎么做呢?
当前回答
JavaScript是最好的选择。下面的链接给出了一个使用按钮取消/全选的例子。你可以尝试调整它来使用复选框,只需使用你的“全选”复选框的onClick属性。
Javascript函数来检查或取消所有复选框
本页有一个更简单的示例
http://www.htmlcodetutorial.com/forms/_INPUT_onClick.html
其他回答
这样就可以完成工作了:
$(':checkbox').each(function() {
this.checked = true;
});
我很惊讶没有人提到document.querySelectorAll()。纯JavaScript解决方案,工作在IE9+。
函数切换(源){ var checkboxes = document.querySelectorAll('input[type="checkbox"]'); For (var I = 0;I < checkboxes.length;我+ +){ If(复选框[i] != source) [我]复选框。Checked = source.checked; } } <input type="checkbox" onclick="切换(此);"/ >检查所有吗?< br / > <input type="checkbox" />Bar 1<br /> <input type="checkbox" />Bar 2<br /> <input type="checkbox" />Bar 3<br /> <input type="checkbox" />Bar 4<br />
使用jQuery和knockout:
由于此绑定主复选框与底层复选框保持同步,除非所有复选框都已选中,否则它将未选中。
ko.bindingHandlers.allChecked = {
init: function (element, valueAccessor) {
var selector = valueAccessor();
function getChecked () {
element.checked = $(selector).toArray().every(function (checkbox) {
return checkbox.checked;
});
}
function setChecked (value) {
$(selector).toArray().forEach(function (checkbox) {
if (checkbox.checked !== value) {
checkbox.click();
}
});
}
ko.utils.registerEventHandler(element, 'click', function (event) {
setChecked(event.target.checked);
});
$(window.document).on('change', selector, getChecked);
ko.utils.domNodeDisposal.addDisposeCallback(element, () => {
$(window.document).off('change', selector, getChecked);
});
getChecked();
}
};
在html中:
<input id="check-all-values" type="checkbox" data-bind="allChecked: '.checkValue'"/>
<input id="check-1" type="checkbox" class="checkValue"/>
<input id="check-2" type="checkbox" class="checkValue"/>
这是一个backbone.js实现:
events: {
"click #toggleChecked" : "toggleChecked"
},
toggleChecked: function(event) {
var checkboxes = document.getElementsByName('options');
for(var i=0; i<checkboxes.length; i++) {
checkboxes[i].checked = event.currentTarget.checked;
}
},
<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>