如何使用 JavaScript 选中/取消选中复选框?
JavaScript:
// Check
document.getElementById("checkbox").checked = true;
// Uncheck
document.getElementById("checkbox").checked = false;
jQuery(1.6+):
// Check
$("#checkbox").prop("checked", true);
// Uncheck
$("#checkbox").prop("checked", false);
jQuery(1.5-):
// Check
$("#checkbox").attr("checked", true);
// Uncheck
$("#checkbox").attr("checked", false);
尚未提及的重要行为:
以编程方式设置 checked 属性,不会触发复选框的
change
事件。
在这个小提琴中亲自看看:
http://jsfiddle.net/fjaeger/L9z9t04p/4/
(Fiddle 在 Chrome 46、Firefox 41 和 IE 11 中测试)
click()
方法有一天,您可能会发现自己编写的代码依赖于被触发的事件。要确保事件触发,请调用复选框元素的
click()
方法,如下所示:
document.getElementById('checkbox').click();
但是,这会切换复选框的选中状态,而不是专门将其设置为
true
或 false
。请记住, change
事件应该仅在选中的属性实际发生更改时触发。
它也适用于 jQuery 方式:使用
prop
或 attr
设置属性,不会触发 change
事件。
checked
设置为特定值您可以在调用
checked
方法之前测试 click()
属性。示例:
function toggle(checked) {
var elm = document.getElementById('checkbox');
if (checked != elm.checked) {
elm.click();
}
}
在此处阅读有关点击方法的更多信息:
https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/click
检查:
document.getElementById("id-of-checkbox").checked = true;
取消选中:
document.getElementById("id-of-checkbox").checked = false;
我们可以选中一个微粒复选框,
$('id of the checkbox')[0].checked = true
然后取消选中,
$('id of the checkbox')[0].checked = false
试试这个:
//Check
document.getElementById('checkbox').setAttribute('checked', 'checked');
//UnCheck
document.getElementById('chk').removeAttribute('checked');
我想指出,将“checked”属性设置为非空字符串会导致选中框。
因此,如果您将 'checked' 属性设置为 "false",则该复选框将被选中。我必须将该值设置为空字符串、null或布尔值false,以确保未选中该复选框。
使用普通js:
//for one element:
document.querySelector('.myCheckBox').checked = true //will select the first matched element
document.querySelector('.myCheckBox').checked = false//will unselect the first matched element
//for multiple elements:
for (const checkbox of document.querySelectorAll('.myCheckBox')) {
//iterating over all matched elements
checkbox.checked = true //for selection
checkbox.checked = false //for unselection
}
function setCheckboxValue(checkbox,value) {
if (checkbox.checked!=value)
checkbox.click();
}
<script type="text/javascript">
$(document).ready(function () {
$('.selecctall').click(function (event) {
if (this.checked) {
$('.checkbox1').each(function () {
this.checked = true;
});
} else {
$('.checkbox1').each(function () {
this.checked = false;
});
}
});
});
</script>
单次检查尝试
myCheckBox.checked=1
<input type="checkbox" id="myCheckBox"> Call to her
多次尝试
document.querySelectorAll('.imChecked').forEach(c=> c.checked=1)
Buy wine: <input type="checkbox" class="imChecked"><br>
Play smooth-jazz music: <input type="checkbox"><br>
Shave: <input type="checkbox" class="imChecked"><br>
.click()
,您可以直接通过其 .checked 属性(一个 IDL 属性)更改其值<input type="checkbox">
)。
注意,这样做不会触发通常相关的事件(change),因此您需要手动触发它以获得可与任何相关事件处理程序一起使用的完整解决方案。
这是一个原始 JavaScript (ES6) 的功能示例:
class ButtonCheck {
constructor() {
let ourCheckBox = null;
this.ourCheckBox = document.querySelector('#checkboxID');
let checkBoxButton = null;
this.checkBoxButton = document.querySelector('#checkboxID+button[aria-label="checkboxID"]');
let checkEvent = new Event('change');
this.checkBoxButton.addEventListener('click', function() {
let checkBox = this.ourCheckBox;
//toggle the checkbox: invert its state!
checkBox.checked = !checkBox.checked;
//let other things know the checkbox changed
checkBox.dispatchEvent(checkEvent);
}.bind(this), true);
this.eventHandler = function(e) {
document.querySelector('.checkboxfeedback').insertAdjacentHTML('beforeend', '<br />Event occurred on checkbox! Type: ' + e.type + ' checkbox state now: ' + this.ourCheckBox.checked);
}
//demonstration: we will see change events regardless of whether the checkbox is clicked or the button
this.ourCheckBox.addEventListener('change', function(e) {
this.eventHandler(e);
}.bind(this), true);
//demonstration: if we bind a click handler only to the checkbox, we only see clicks from the checkbox
this.ourCheckBox.addEventListener('click', function(e) {
this.eventHandler(e);
}.bind(this), true);
}
}
var init = function() {
const checkIt = new ButtonCheck();
}
if (document.readyState != 'loading') {
init;
} else {
document.addEventListener('DOMContentLoaded', init);
}
<input type="checkbox" id="checkboxID" />
<button aria-label="checkboxID">Change the checkbox!</button>
<div class="checkboxfeedback">No changes yet!</div>
如果您运行它并单击复选框和按钮,您应该了解它是如何工作的。
请注意,我使用 document.querySelector 是为了简洁/简单,但这可以很容易地构建为将给定 ID 传递给构造函数,或者它可以应用于充当复选框的 aria 标签的所有按钮(请注意我没有费心在按钮上设置 id 并为复选框提供 aria-labelledby(如果使用此方法,则应该这样做)或任何其他方法来扩展它。最后两个
addEventListener
只是为了演示它是如何工作的。
我同意当前的答案,但就我而言,它不起作用,我希望这段代码可以帮助将来的人:
// check
$('#checkbox_id').click()
所以我经常有多个具有相同输入名称的复选框,因此在发布时它们最终会很好地分组。 要取消选中该输入名称的所有复选框,我使用如下内容:
for (const cbe of document.querySelectorAll('[name=xxx]')) {
cbe.checked = false;
}