使用 JavaScript(jQuery 或 vanilla)选中/取消选中复选框?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8206565/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Check/Uncheck checkbox with JavaScript (jQuery or vanilla)?
提问by lisovaccaro
How can a checkbox be checked/unchecked using JavaScript, jQuery or vanilla?
如何使用 JavaScript、jQuery 或 vanilla 选中/取消选中复选框?
回答by Alex Peattie
Javascript:
Javascript:
// Check
document.getElementById("checkbox").checked = true;
// Uncheck
document.getElementById("checkbox").checked = false;
jQuery (1.6+):
jQuery (1.6+):
// Check
$("#checkbox").prop("checked", true);
// Uncheck
$("#checkbox").prop("checked", false);
jQuery (1.5-):
jQuery (1.5-):
// Check
$("#checkbox").attr("checked", true);
// Uncheck
$("#checkbox").attr("checked", false);
回答by sudoqux
Important behaviour that has not yet been mentioned:
尚未提及的重要行为:
Programmatically setting the checkedattribute, does not fire the changeevent of the checkbox.
以编程方式设置checked属性,不会触发changecheckbox的事件。
See for yourself in this fiddle:
http://jsfiddle.net/fjaeger/L9z9t04p/4/
在这个小提琴中亲眼看看:http:
//jsfiddle.net/fjaeger/L9z9t04p/4/
(Fiddle tested in Chrome 46, Firefox 41 and IE 11)
(Fiddle 在 Chrome 46、Firefox 41 和 IE 11 中测试)
The click()method
该click()方法
Some day you might find yourself writing code, which relies on the event being fired. To make sure the event fires, call the click()method of the checkbox element, like this:
有一天你可能会发现自己在编写代码,这依赖于被触发的事件。要确保事件触发,请调用click()复选框元素的方法,如下所示:
document.getElementById('checkbox').click();
However, this toggles the checked status of the checkbox, instead of specifically setting it to trueor false. Remember that the changeevent should only fire, when the checked attribute actually changes.
但是,这会切换复选框的选中状态,而不是专门将其设置为true或false。请记住,该change事件只应在已检查的属性实际更改时触发。
It also applies to the jQuery way: setting the attribute using propor attr, does not fire the changeevent.
它也适用于 jQuery 方式:使用propor设置属性attr不会触发change事件。
Setting checkedto a specific value
设置checked为特定值
You could test the checkedattribute, before calling the click()method. Example:
您可以checked在调用该click()方法之前测试该属性。例子:
function toggle(checked) {
var elm = document.getElementById('checkbox');
if (checked != elm.checked) {
elm.click();
}
}
Read more about the click method here:
https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/click
在此处阅读有关点击方法的更多信息:https:
//developer.mozilla.org/en-US/docs/Web/API/HTMLElement/click
回答by topherg
to check:
去检查:
document.getElementById("id-of-checkbox").checked = true;
to uncheck:
取消选中:
document.getElementById("id-of-checkbox").checked = false;
回答by AKS
We can checked a particulate checkbox as,
我们可以检查一个微粒复选框,
$('id of the checkbox')[0].checked = true
and uncheck by ,
并取消选中,
$('id of the checkbox')[0].checked = false
回答by Jan Rasehorn
I would like to note, that setting the 'checked' attribute to a non-empty string leads to a checked box.
我想指出,将 'checked' 属性设置为非空字符串会导致选中的框。
So if you set the 'checked' attribute to "false", the checkbox will be checked. I had to set the value to the empty string, nullor the boolean value falsein order to make sure the checkbox was not checked.
因此,如果您将 'checked' 属性设置为"false",复选框将被选中。我必须将该值设置为空字符串、null或布尔值false以确保未选中复选框。
回答by Syed Jamil Uddin
Try This:
尝试这个:
//Check
document.getElementById('checkbox').setAttribute('checked', 'checked');
//UnCheck
document.getElementById('chk').removeAttribute('checked');
回答by kandi
function setCheckboxValue(checkbox,value) {
if (checkbox.checked!=value)
checkbox.click();
}
回答by M.Owais
<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>
回答by taswyn
If, for some reason, you don't want to (or can't) run a .click()on the checkbox element, you can simply change its value directly via its .checked property (an IDL attributeof <input type="checkbox">).
如果由于某种原因,你不希望(或不能)运行.click()的复选框元素上,你可以简单地直接通过其.checked财产(的改变其值IDL属性的<input type="checkbox">)。
Notethat doing so does not fire the normally related event (change) so you'll need to manually fire it to have a complete solution that works with any related event handlers.
请注意,这样做不会触发通常相关的事件 ( change),因此您需要手动触发它以获得可与任何相关事件处理程序一起使用的完整解决方案。
Here's a functional example in raw javascript (ES6):
这是原始 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>
If you run this and click on both the checkbox and the button you should get a sense of how this works.
如果您运行它并单击复选框和按钮,您应该了解它是如何工作的。
Note that I used document.querySelector for brevity/simplicity, but this could easily be built out to either have a given ID passed to the constructor, or it could apply to all buttons that act as aria-labels for a checkbox (note that I didn't bother setting an id on the button and giving the checkbox an aria-labelledby, which should be done if using this method) or any number of other ways to expand this. The last two addEventListeners are just to demo how it works.
请注意,我使用 document.querySelector 是为了简洁/简单,但这可以很容易地构建为将给定的 ID 传递给构造函数,或者它可以应用于充当复选框的 aria-labels 的所有按钮(请注意,我没有费心在按钮上设置 id 并给复选框一个 aria-labelledby,如果使用这种方法应该这样做)或任何其他方法来扩展它。最后两个addEventListener只是为了演示它是如何工作的。
回答by Kamil Kie?czewski
For single check try
对于单一检查尝试
myCheckBox.checked=1
<input type="checkbox" id="myCheckBox"> Call to her
for multi try
多次尝试
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>

