JavaScript的复选框

Check/Uncheck checkbox with JavaScript

本文关键字:复选框 JavaScript      更新时间:2023-09-26

如何使用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);

尚未提及的重要行为:

以编程方式设置选中的属性,不触发复选框change事件。

你自己看:
http://jsfiddle.net/fjaeger/L9z9t04p/4/

(在Chrome 46, Firefox 41和IE 11中测试)

click()方法

有一天你可能会发现自己编写的代码依赖于被触发的事件。为了确保事件被触发,调用checkbox元素的click()方法,如下所示:

document.getElementById('checkbox').click();

但是,这会切换复选框的选中状态,而不是将其具体设置为truefalse。请记住,change事件应该只在被检查的属性发生实际变化时触发。

这也适用于jQuery的方式:使用propattr设置属性,不触发change事件

设置checked为指定值

您可以在调用click()方法之前测试checked属性。例子:

function toggle(checked) {
  var elm = document.getElementById('checkbox');
  if (checked != elm.checked) {
    elm.click();
  }
}

点击这里阅读更多关于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

Try This:

//Check
document.getElementById('checkbox').setAttribute('checked', 'checked');
//UnCheck
document.getElementById('chk').removeAttribute('checked');

我要注意,将'checked'属性设置为非空字符串将导致选中框。

所以如果你将'checked'属性设置为"false",复选框将被选中。我必须将值设置为空字符串null或布尔值false,以确保复选框未被选中。

Using vanilla 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

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>

如果,出于某种原因,您不想(或不能)在复选框元素上运行.click(),您可以简单地通过它的.checked属性(<input type="checkbox">的IDL属性)直接更改其值。

注意这样做不会触发通常相关的事件(更改),因此您需要手动触发它以获得与任何相关事件处理程序一起工作的完整解决方案。

下面是一个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-label的所有按钮(请注意,我没有在按钮上设置ID并为复选框提供aria-labelledby,如果使用此方法应该这样做)或任何其他方法来扩展它。最后两个addEventListener只是为了演示它是如何工作的。

我同意当前的答案,但在我的情况下它不起作用,我希望这段代码在将来帮助别人:

// check
$('#checkbox_id').click()

所以我经常有多个具有相同输入名称的复选框,因此在张贴时它们最终会很好地分组。要取消选中该输入名的所有复选框,我使用如下命令:

for (const cbe of document.querySelectorAll('[name=xxx]')) {
    cbe.checked = false;
}