0% found this document useful (0 votes)
127 views8 pages

Check Uncheck Checkbox With Javascript Jquery or Vanilla 1

The document is a Stack Overflow post discussing how to check and uncheck checkboxes with JavaScript, jQuery, or vanilla JavaScript. The top answer provides code samples to check and uncheck a checkbox by setting its "checked" property to true or false using JavaScript, jQuery 1.6+, and jQuery 1.5-. Subsequent answers discuss additional ways to check and uncheck checkboxes, including by calling the click() method, dispatching change events, and using setAttribute() and removeAttribute().

Uploaded by

Assalam Azeem
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
127 views8 pages

Check Uncheck Checkbox With Javascript Jquery or Vanilla 1

The document is a Stack Overflow post discussing how to check and uncheck checkboxes with JavaScript, jQuery, or vanilla JavaScript. The top answer provides code samples to check and uncheck a checkbox by setting its "checked" property to true or false using JavaScript, jQuery 1.6+, and jQuery 1.5-. Subsequent answers discuss additional ways to check and uncheck checkboxes, including by calling the click() method, dispatching change events, and using setAttribute() and removeAttribute().

Uploaded by

Assalam Azeem
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

Stack Overflow sign up log in

Questions Jobs Tags Users Badges Ask

466 Check/Uncheck checkbox with JavaScript (jQuery or Vanilla)?


javascript jquery

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


vanilla?

share improve this question

lisovaccaro asked
7,929 ●● 80 ●● 218 ●● 365 Nov 21 '11 at 2:12

Mooseman edited
16.7k ●● 11 ●● 61 ●● 85 Apr 21 at 22:49

2 possible duplicate of modify checkbox using javascript – mauris Nov 21 '11 at 2:17

add a comment

10 Answers order by votes

Javascript:
865
// Check
document.getElementById("checkbox").cchheecckkeedd = ttrruuee;

// Uncheck
document.getElementById("checkbox").cchheecckkeedd = ffaallssee;

jQuery (1.6+):

// Check
$("#checkbox").prop("checked", ttrruuee);

// Uncheck
$("#checkbox").prop("checked", ffaallssee);

jQuery (1.5-):

// Check
$("#checkbox").attr("checked", ttrruuee);

By using our site, you acknowledge that you have read and understand our Cookie
Policy, Privacy Policy, and our Terms of Service.
share improve this answer

Alex Peattie answered


19.9k ●● 5 ●● 43 ●● 51 Nov 21 '11 at 2:14

andreas edited
12.6k ●● 10 ●● 48 ●● 57 Dec 16 '16 at 17:28

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); ``` – Andrew
Downes Mar 27 '15 at 10:27

3 Should we rather use attr or prop ? – Black Aug 30 '16 at 7:31

@Black see stackoverflow.com/questions/5874652/prop-vs-attr – Andre Figueiredo


Jan 27 at 17:14

8 Apparently .checked = true/false doesn't trigger the change event :-\ – leaf
Mar 1 at 9:13

add a comment

By using our site, you acknowledge that you have read and understand our Cookie
Policy, Privacy Policy, and our Terms of Service.
Important behaviour that has not yet been mentioned:
115
Programmatically setting the checked attribute, does not fire the
cchhaannggee 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 cclliicckk(()) 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 cchheecckkeedd to a specific value


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

ffuunnccttiioonn toggle(cchheecckkeedd) {
vvaarr elm = document.getElementById('checkbox');
iiff (cchheecckkeedd != elm.cchheecckkeedd) {
elm.click();
}
}

Read more about the click method here:


https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement
/click

share improve this answer

franzjaeger answered
1,328 ●● 1 ●● 9 ●● 9 Oct 30 '15 at 10:05

8 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')); – Victor
Sharovatov Feb 6 '16 at 8:48

By using our site, you acknowledge that you have read and understand our Cookie
Policy, Privacy Policy, and our Terms of Service.
2 I can agree only partially - many web browsers with AdBlocks are defending DOM
from virtual clicking() due to unwanted actions from ads – pkolawa Sep 12 '17 at
8:36

2 @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. – Bill Dagg Mar 28 at
19:34

add a comment

to check:
34
document.getElementById("id-of-checkbox").cchheecckkeedd = ttrruuee;

to uncheck:

document.getElementById("id-of-checkbox").cchheecckkeedd = ffaallssee;

share improve this answer

topherg answered
2,560 ●● 3 ●● 26 ●● 62 Nov 21 '11 at 2:14

jtheletter edited
7,054 ●● 4 ●● 36 ●● 45 Jan 30 '18 at 20:10

1 That would only change the checked attribute. However, onclick and similar events
will not be triggered. – Paul Stelian Jun 28 '18 at 19:06

add a comment

We can checked a particulate checkbox as,


15
$('id of the checkbox')[0].cchheecckkeedd = ttrruuee

and uncheck by ,

$('id of the checkbox')[0].cchheecckkeedd = ffaallssee

share improve this answer

AKS answered
209 ●● 3 ●● 2 Apr 9 '15 at 1:52

Amit Joki edited

By using our site, you acknowledge that you have read and understand our Cookie
Policy, Privacy Policy, and our Terms of Service.
1 You really don't need the array index if you are only selecting one element. But I
guess if you want to be explicit. haha – Rizowski Apr 22 '15 at 18:46

5 @Rizowski You do need the index to get the native html element - jQuery objects
don't have a "checked" property – Henrik Christensen Sep 7 '15 at 11:55

But we might as well just be using the jQuery at that point – damd Apr 13 '16 at
20:05

This has worked for me. Without the array index, I were getting undefined error.
Thanks so much, saved my day. – Neri Apr 15 '18 at 12:37

add a comment

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


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

share improve this answer

Jan Rasehorn answered


216 ●● 2 ●● 5 Nov 16 '15 at 17:02

edited
Nov 16 '15 at 17:08

3 This is because a non-empty string is regarded as truthy. – James Coyle Jan 5 '16 at
15:55

add a comment

Try This:
8
//Check
document.getElementById('checkbox').setAttribute('checked'

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

share improve this answer

Syed Jamil Uddin answered


149 ●● 1 ●● 5 Mar 4 '16 at 12:16

By using our site, you acknowledge that you have read and understand our Cookie
Policy, Privacy Policy, and our Terms of Service.
<<ssccrriipptt type="text/javascript">>
5
$(document).ready(ffuunnccttiioonn () {
$('.selecctall').click(ffuunnccttiioonn (event) {
iiff (tthhiiss.checked) {
$('.checkbox1').each(ffuunnccttiioonn () {
tthhiiss.checked = ttrruuee;
});
} eellssee {
$('.checkbox1').each(ffuunnccttiioonn () {
tthhiiss.checked = ffaallssee;
});
}
});

});

<<//ssccrriipptt>>

share improve this answer

M.Owais answered
71 ●● 1 ●● 2 Mar 4 '16 at 11:40

ffuunnccttiioonn setCheckboxValue(checkbox,value) {
4
iiff (checkbox.cchheecckkeedd!=value)
checkbox.click();
}

share improve this answer

kandi answered
326 ●● 4 ●● 19 Aug 24 '16 at 12:40

By using our site, you acknowledge that you have read and understand our Cookie
Policy, Privacy Policy, and our Terms of Service.
If, for some reason, you don't want to (or can't) run a .click() on the
1 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):

ccllaassss BBuuttttoonnCChheecckk {
ccoonnssttrruuccttoorr() {
lleett ourCheckBox = nnuullll;
tthhiiss.ourCheckBox = document.querySelector('#checkboxID'

lleett checkBoxButton = nnuullll;


tthhiiss.checkBoxButton = document.querySelector('#checkboxID+butt

lleett checkEvent = nneeww EEvveenntt('change');

tthhiiss.checkBoxButton.addEventListener('click', ffuunnccttiioonn
lleett checkBox = tthhiiss.ourCheckBox;

//toggle the checkbox: invert its state!


checkBox.checked = !checkBox.checked;

//let other things know the checkbox changed


checkBox.dispatchEvent(checkEvent);
}.bind(tthhiiss), ttrruuee);

<<iinnppuutt type="checkbox" id="checkboxID" //>>

<<bbuuttttoonn aria-label="checkboxID">>Change the checkbox!<<//bbuuttttoonn>>

<<ddiivv class="checkboxfeedback">>No changes yet!<<//ddiivv>>

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.

share improve this answer

taswyn answered
3,423 ●● 2 ●● 15 ●● 31 Jun 26 '18 at 22:53

edited
Jun 27 '18 at 17:56

By using our site, you acknowledge that you have read and understand our Cookie
Policy, Privacy Policy, and our Terms of Service.
If you want to use the TypeScript, you can do like this:
-3
ffuunnccttiioonn defaultCheckedFirst(checkGroup: any): vvooiidd {
ffoorr (lleett i = 0; i < checkGroup.length; i++) {
(<HHTTMMLLIInnppuuttEElleemmeenntt>radionGroups[i]).checked =
}
}

share improve this answer

Ortsbo answered
113 ●● 1 ●● 5 Aug 9 '18 at 21:54

Not sure how this is helpful, OP asked "JavaScript or jQuery". It is a fair assumption
that they don't want to swap to TypeScript for this simple function. Also, why this
condition (i === 0 ? true : false) ? – RossBille Aug 13 '18 at 22:24

It's another idea and solution. TypeScript is a typed superset of JavaScript that
compiles to plain JavaScript. The Condition ( i === 0 ? true : false) is the conditional
(ternary) operator. We can reused this function and set true or false value to
checkbox group. – Ortsbo Aug 15 '18 at 3:31

I understand what typescript is, but this answer doesn't add any value to the
question. As for the condition, it doesn't help with reusability at all. It will ensure that
you check the first element, and uncheck the rest. This all assumes that your cast
works. – RossBille Aug 16 '18 at 6:27

add a comment

meta chat tour help blog privacy policy legal contact us full site
2019 Stack Exchange, Inc

By using our site, you acknowledge that you have read and understand our Cookie
Policy, Privacy Policy, and our Terms of Service.

You might also like