Alex Rivera | Logout

Setting "checked" for a checkbox with jQuery

Asked 2009-01-08T22:20:24.913
4608

I'd like to do something like this to tick a checkbox using jQuery:

$(".myCheckBox").checked(true);

or

$(".myCheckBox").selected(true);

Does such a thing exist?

Edit
Report

4 Answers

168

You can do

$('.myCheckbox').attr('checked',true) //Standards compliant

or

$("form #mycheckbox").attr('checked', true)

If you have custom code in the onclick event for the checkbox that you want to fire, use this one instead:

$("#mycheckbox").click();

You can uncheck by removing the attribute entirely:

$('.myCheckbox').removeAttr('checked')

You can check all checkboxes like this:

$(".myCheckbox").each(function(){
    $("#mycheckbox").click()
});
answered 2009-01-08T22:24:24.483
51

Assuming that the question is...

How do I check a checkbox-set BY VALUE?

Remember that in a typical checkbox set, all input tags have the same name, they differ by the attribute value: there are no ID for each input of the set.

Xian's answer can be extended with a more specific selector, using the following line of code:

$("input.myclass[name='myname'][value='the_value']").prop("checked", true);
answered 2012-03-09T12:28:49.063
40

Here is a way to do it without jQuery

function addOrAttachListener(el, type, listener, useCapture) {
  if (el.addEventListener) {
    el.addEventListener(type, listener, useCapture);
  } else if (el.attachEvent) {
    el.attachEvent("on" + type, listener);
  }
};

addOrAttachListener(window, "load", function() {
  var cbElem = document.getElementById("cb");
  var rcbElem = document.getElementById("rcb");
  addOrAttachListener(cbElem, "click", function() {
    rcbElem.checked = cbElem.checked;
  }, false);
}, false);
<label>Click Me!
  <input id="cb" type="checkbox" />
</label>
<label>Reflection:
  <input id="rcb" type="checkbox" />
</label>

answered 2012-10-23T00:41:23.697
33

Try this:

$('#checkboxid').get(0).checked = true;  //For checking

$('#checkboxid').get(0).checked = false; //For unchecking
answered 2012-09-10T10:26:10.500

Your Answer