Check/Uncheck checkbox with JavaScript (jQuery or vanilla)?

后端 未结 12 1287
渐次进展
渐次进展 2020-11-22 09:39

How can a checkbox be checked/unchecked using JavaScript, jQuery or vanilla?

12条回答
  •  失恋的感觉
    2020-11-22 10:21

    Important behaviour that has not yet been mentioned:

    Programmatically setting the checked attribute, does not fire the change event of the checkbox.

    See for yourself in this fiddle:
    http://jsfiddle.net/fjaeger/L9z9t04p/4/

    (Fiddle tested in Chrome 46, Firefox 41 and IE 11)

    The click() method

    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:

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

    However, this toggles the checked status of the checkbox, instead of specifically setting it to true or false. Remember that the change event should only fire, when the checked attribute actually changes.

    It also applies to the jQuery way: setting the attribute using prop or attr, does not fire the change event.

    Setting checked to a specific value

    You could test the checked attribute, before calling the click() method. Example:

    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

提交回复
热议问题