[javascript] Check/Uncheck checkbox with JavaScript

How can a checkbox be checked/unchecked using JavaScript?

This question is related to javascript checkbox

The answer is


vanilla (PHP) will check box on and off and store result.

<?php
    if($serverVariable=="checked") 
        $checked = "checked";
    else
        $checked = "";
?>
<input type="checkbox"  name="deadline" value="yes" <?= $checked 
?> >

# on server
<?php
        if(isset($_POST['deadline']) and
             $_POST['deadline']=='yes')
             $serverVariable = checked;    
        else
             $serverVariable = "";  
?>

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()

function setCheckboxValue(checkbox,value) {
    if (checkbox.checked!=value)
        checkbox.click();
}

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.


We can checked a particulate checkbox as,

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

and uncheck by ,

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

to check:

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

to uncheck:

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

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

For single check try

_x000D_
_x000D_
myCheckBox.checked=1
_x000D_
<input type="checkbox" id="myCheckBox"> Call to her
_x000D_
_x000D_
_x000D_

for multi try

_x000D_
_x000D_
document.querySelectorAll('.imChecked').forEach(c=> c.checked=1)
_x000D_
Buy wine: <input type="checkbox" class="imChecked"><br>_x000D_
Play smooth-jazz music: <input type="checkbox"><br>_x000D_
Shave: <input type="checkbox" class="imChecked"><br>
_x000D_
_x000D_
_x000D_


Try This:

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

//UnCheck
document.getElementById('chk').removeAttribute('checked');

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):

_x000D_
_x000D_
class ButtonCheck {_x000D_
  constructor() {_x000D_
    let ourCheckBox = null;_x000D_
    this.ourCheckBox = document.querySelector('#checkboxID');_x000D_
_x000D_
    let checkBoxButton = null;_x000D_
    this.checkBoxButton = document.querySelector('#checkboxID+button[aria-label="checkboxID"]');_x000D_
_x000D_
    let checkEvent = new Event('change');_x000D_
    _x000D_
    this.checkBoxButton.addEventListener('click', function() {_x000D_
      let checkBox = this.ourCheckBox;_x000D_
_x000D_
      //toggle the checkbox: invert its state!_x000D_
      checkBox.checked = !checkBox.checked;_x000D_
_x000D_
      //let other things know the checkbox changed_x000D_
      checkBox.dispatchEvent(checkEvent);_x000D_
    }.bind(this), true);_x000D_
_x000D_
    this.eventHandler = function(e) {_x000D_
      document.querySelector('.checkboxfeedback').insertAdjacentHTML('beforeend', '<br />Event occurred on checkbox! Type: ' + e.type + ' checkbox state now: ' + this.ourCheckBox.checked);_x000D_
_x000D_
    }_x000D_
_x000D_
_x000D_
    //demonstration: we will see change events regardless of whether the checkbox is clicked or the button_x000D_
_x000D_
    this.ourCheckBox.addEventListener('change', function(e) {_x000D_
      this.eventHandler(e);_x000D_
    }.bind(this), true);_x000D_
_x000D_
    //demonstration: if we bind a click handler only to the checkbox, we only see clicks from the checkbox_x000D_
_x000D_
    this.ourCheckBox.addEventListener('click', function(e) {_x000D_
      this.eventHandler(e);_x000D_
    }.bind(this), true);_x000D_
_x000D_
_x000D_
  }_x000D_
}_x000D_
_x000D_
var init = function() {_x000D_
  const checkIt = new ButtonCheck();_x000D_
}_x000D_
_x000D_
if (document.readyState != 'loading') {_x000D_
  init;_x000D_
} else {_x000D_
  document.addEventListener('DOMContentLoaded', init);_x000D_
}
_x000D_
<input type="checkbox" id="checkboxID" />_x000D_
_x000D_
<button aria-label="checkboxID">Change the checkbox!</button>_x000D_
_x000D_
<div class="checkboxfeedback">No changes yet!</div>
_x000D_
_x000D_
_x000D_

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.


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