Check/Uncheck checkbox with JavaScript
Asked Answered
B

13

851

How can a checkbox be checked/unchecked using JavaScript?

Bovid answered 21/11, 2011 at 2:12 Comment(1)
possible duplicate of modify checkbox using javascriptSlambang
R
1464

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);
Ropable answered 21/11, 2011 at 2:14 Comment(5)
Using .prop doesn't seem to work with Jquery 1.11.2 in Firefox with locally hosted files. .attr does. I've not tested more fully. Here's the code: ``` personContent.find("[data-name='" + pass.name + "']").children('input').attr('checked', true); ```Gunyah
Should we rather use attr or prop ?Importunate
Apparently .checked = true/false doesn't trigger the change event :-\Ayurveda
fyi: just tested this onclick="document.getElementById('dmsmh_chk').checked = !document.getElementById('dmsmh_chk').checked;" this behaves like a jQuery toggle in plain JS. (checks the box when it is unchecked or removes the check when it is checked)Furbelow
what if I'm using "document.getElementsByClassName("chkbx")" and multiple checkboxes are being returned?Isabeau
C
225

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

Cryobiology answered 30/10, 2015 at 10:5 Comment(4)
That's a good answer but personally I would prefer to fire the change event instead of calling the click() elm.dispatchEvent(new Event('change'));Quadriceps
@VictorSharovatov Why would you prefer to fire the change event?Incurrence
I can agree only partially - many web browsers with AdBlocks are defending DOM from virtual clicking() due to unwanted actions from adsKorea
@PeterCo: Probably because it more-clearly portrays intent -- click the element to fire the change event versus dispatch a change event to fire a change event -- indirect (click triggers change) versus direct. The latter is considerably clearer and doesn't require the reader to know that a click fires a change.Yasmin
P
47

to check:

document.getElementById("id-of-checkbox").checked = true;

to uncheck:

document.getElementById("id-of-checkbox").checked = false;
Paresh answered 21/11, 2011 at 2:14 Comment(1)
That would only change the checked attribute. However, onclick and similar events will not be triggered.Legging
D
22

We can checked a particulate checkbox as,

$('id of the checkbox')[0].checked = true

and uncheck by ,

$('id of the checkbox')[0].checked = false
Disbelief answered 9/4, 2015 at 1:52 Comment(4)
You really don't need the array index if you are only selecting one element. But I guess if you want to be explicit. hahaSomniferous
@Somniferous You do need the index to get the native html element - jQuery objects don't have a "checked" propertyDisherison
This has worked for me. Without the array index, I were getting undefined error. Thanks so much, saved my day.Engineer
Works perfect! It is only working with [0] because the object does not have the property, so we need the index. No idea why this answer isn't the most upvoted answer...Roseboro
S
19

Try This:

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

//UnCheck
document.getElementById('chk').removeAttribute('checked');
Selfabsorbed answered 4/3, 2016 at 12:16 Comment(1)
Your answer has a limitation. When the checkbox is checked or unchecked at least once by the end user, i.e not programmatically, it stops working, the same checkbox can no longer be checked or unchecked programmatically by setting this attribute. I've just tested under Mozilla Firefox 94.0.2 and Microsoft Edge 96.0.1054.43. However, document.getElementById('checkbox').checked = true and document.getElementById('checkbox').checked = false work as expected (but don't trigger a change event as stated in many posts).Sentiment
S
17

I would like to note, that setting the 'checked' attribute to a non-empty string leads to a checked box.

So if you set the 'checked' attribute to "false", the checkbox will be checked. I had to set the value to the empty string, null or the boolean value false in order to make sure the checkbox was not checked.

Stricker answered 16/11, 2015 at 17:2 Comment(1)
This is because a non-empty string is regarded as truthy.Gentianaceous
C
17

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
}
Cinch answered 29/7, 2021 at 7:10 Comment(0)
A
11
function setCheckboxValue(checkbox,value) {
    if (checkbox.checked!=value)
        checkbox.click();
}
Aerograph answered 24/8, 2016 at 12:40 Comment(0)
G
6
<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>
Glarum answered 4/3, 2016 at 11:40 Comment(0)
D
6

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>
Dolora answered 27/12, 2019 at 22:13 Comment(0)
M
5

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 attribute of <input type="checkbox">).

Note that 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.

Here's a functional example in raw 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.

Mieshamiett answered 26/6, 2018 at 22:53 Comment(0)
C
1

I agree with the current answers, but in my case it does not work, I hope this code help someone in the future:

// check
$('#checkbox_id').click()
Culicid answered 25/2, 2020 at 7:56 Comment(2)
This work if you are using jQuery. The question is about solving it using vanilla jsCinch
This is very useful if you've got onclick() events ties to the checkbox and you want to trigger them. Simply chaning prop('checked', true) will not trigger the events.Forficate
S
1

So I often have multiple checkboxes with the same input name, so they end up grouped nicely when POSTing. To uncheck all checkboxes for that input name, I use something like this:

for (const cbe of document.querySelectorAll('[name=xxx]')) {
    cbe.checked = false;
}
Sigfried answered 4/7, 2023 at 8:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.