Check/Uncheck checkbox with JavaScript - javascript

How can a checkbox be checked/unchecked using JavaScript?

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

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

to check:
document.getElementById("id-of-checkbox").checked = true;
to uncheck:
document.getElementById("id-of-checkbox").checked = false;

We can checked a particulate checkbox as,
$('id of the checkbox')[0].checked = true
and uncheck by ,
$('id of the checkbox')[0].checked = false

Try This:
//Check
document.getElementById('checkbox').setAttribute('checked', 'checked');
//UnCheck
document.getElementById('chk').removeAttribute('checked');

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.

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
}

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

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

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.

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

Related

How can I check the checkbox with mousedown event?

I have the following code:
checkbox.addEventListener('mousedown', function () {
if (!this.checked) {
this.checked = true;
}
});
It should turn on the checkbox when mouse button is down.
And it works perfectly but when I release the button, the checkbox turns back off. How can i fix this?
checkbox.addEventListener('mousedown', function(){
if(!this.checked) {
var preventUnselect = function(){
this.checked = true;
checkbox.removeEventListener('click', preventUnselect)
};
checkbox.addEventListener('click', preventUnselect)
this.checked = true;
}
});
<input type="checkbox" id="checkbox"/>
I'm pretty sure that your checkbox gets unchecked because default behavior of checkbox is to change it's state after click. If you check checkbox after mousedown, then it's state get switched(turned back to unchecked) after click event completes. Just click the checkbox and move the pointer outside of it while still holding left mouse key down - checkbox won't get unchecked when you release the button..
You have to bind click event after mousedown, and remove that event afterward. If event wasn't removed your checkbox would be checked forever.
checkbox.addEventListener('mousedown', function(){
this.checked = !this.checked;
});
Note that checkboxes already have this behaviour as a default built into it by the browsers. I you want to see if a checkbox is checked or not you can simply look at the checked property of the DOM element. For example:
const checkbox = document.getElementById('Mycheckbox');
// this onclick now purely for demonstration purposes
checkbox.addEventListener('click', function () {
console.log(checkbox.checked);
});
<input type="checkbox" id="Mycheckbox"/>

How to stop event bubbling in jquery?

I'm using some JQ stuff on check box, even if the parent div is clicked. I am toggling the value of check box. Clicking on div is working perfectly but when you click on checkbox the function is called twice. Is there any way to solve this problem? following is my code(Fiddle)
HTML:
<div class="check-unit">
<input type="checkbox" class="check" />
<p class="brandList">Model</p>
</div>
JQ:
$('.check').on('change',function(e){
e.stopImmediatePropagation();
if($(this).is(':checked')){
console.log("checked");
}else{
console.log("unchecked");
}
});
$('.check-unit').on('click',function(e){
var checkbox = $(this).children('.check'),
chhhk= checkbox.attr('checked') ? false : true;
checkbox.attr('checked',chhhk);
$(this).children('.check').change();
});
I've seen eventbubbling problem on stackoverflow, but still confused how to do this. FIDDLE
Only execute the callback on the parent element if the target is not the input
$('.check').on('change',function(e){
if(this.checked){
console.log("checked");
}else{
console.log("unchecked");
}
});
$('.check-unit').on('click',function(e){
if ( ! $(e.target).hasClass('check')) {
$(this).children('.check').prop('checked', function(_,state) {
return !state;
}).trigger('change');
}
});
FIDDLE
As a sidenote, this is what label elements are for!
You need to use .prop() instead of .attr() to set the checked property.
$('.check').on('change', function (e) {
if (this.checked) {
console.log("checked");
} else {
console.log("unchecked");
}
}).click(function (e) {
//prevent clicks in the checksboxes from bubbling up otherwise when you click on the checkbox the state will get toggled again the event will be bubbled to check-unit which will again toggle the state negating the click
e.stopPropagation()
});
$('.check-unit').on('click', function () {
var checkbox = $(this).children('.check'),
//use .is() and checked-selector to check whether the checkbox is checked
chhhk = checkbox.is(':checked');
//use .prop() instead of .attr() & toggle the checked state
checkbox.prop('checked', !chhhk).change();
});
Demo: Fiddle
You can check if you are clicking the checkbox before changing.
$('.check-unit').on('click', function (e) {
if (!($(e.target).hasClass('check'))) {
var checkbox = $(this).children('.check'),
chhhk = checkbox.prop('checked');
checkbox.prop('checked', !chhhk).change();
}
});
Also note that the code is using prop instead of attr because when you are using boolean attribute values you should use .prop()
DEMO

Why isn't jquery detecting when a radio button is unchecked? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
JQuery $(#radioButton).change(…) not firing during de-selection
I have the following HTML/jQuery:
<input id="rb1" type="radio" name="rb" checked="true">
<input id="rb2" type="radio" name="rb">
$("#rb2").change(function () {
if ($(this).is(":checked")) {
alert('checked');
}
else {
alert('unchecked');
}
});
When my rb2 radio button is unselected by selecting rb1, the change event does not fire. Why is this? Is it possible to get this working without changing my selector to match both inputs and then looking at the ID?
Fiddle: http://jsfiddle.net/4uRWR/
The change event only gets sent when you actually modify the item itself. When you click the other radio, you aren't modifying it. A fix would be to watch the change event on every input:radio, then just check the state of the relevant radio button:
$("input:radio").change(function () {
if ($("#rb2").is(":checked")) {
alert('checked');
}
else {
alert('unchecked');
}
});
http://codepen.io/AlienHoboken/pen/akwjB
Listen for change on every input related to your group of radios and then check if a specific one is selected.
$("input[name=rb]").change(function () {
if ($('#rb2').is(":checked")) {
alert('checked');
} else {
alert('unchecked');
}
});
http://jsfiddle.net/4uRWR/2/
You can artificially trigger a "change" on radio buttons from the same group so that the original bound handler would get picked up and output "unchecked". The trick is to avoid being stuck in an infinite loop by recursively re-triggering the event, we can avoid that by ignoring artificial events that lack the originalEvent property:
$("input[type=radio]").on("change", function (e) {
var $this = $(this);
//all inputs with the same name
var $targetInputSelector = $("input[name=" + $this.attr("name") + "]");
//check if the handler was fired "naturally"
//if yes, trigger the change handler "artificially" for inputs with the same name
if (e.hasOwnProperty('originalEvent')) {
//exclude the element that was changed "naturally"
//from the subset of all the elements with the same name
$targetInputSelector.not($this).triggerHandler("change");
}
});
This code works when added on top of your current handler and satisfies the without changing my selector to match both inputs and then looking at the ID criteria ;)
http://jsfiddle.net/a73tn/24/
I sorta ran into this issue a few days ago. Instead of listening for an individual click on a radio button, I listen for a click on the <ul> I have them in and then call this function to check if one has been selected.
// Iterate over the radio group and determine if one of them is selected
function loopRadBtns(btnGroup)
{
var isChecked = false;
btnGroup.find('input[type="radio"]').each(function()
{
if($(this).attr('checked'))
{
isChecked = true;
}
});
return isChecked;
}

toggle checkbox attribute with jquery [duplicate]

I've used a hover function where you do x on mouseover and y and mouseout. I'm trying the same for click but it doesn't seem to work:
$('.offer').click(function(){
$(this).find(':checkbox').attr('checked', true );
},function(){
$(this).find(':checkbox').attr('checked', false );
});
I want the checkbox to be checked when clicking on a div, and unchecked if clicked again - a click toggle.
This is easily done by flipping the current 'checked' state of the checkbox upon each click. Examples:
$(".offer").on("click", function () {
var $checkbox = $(this).find(':checkbox');
$checkbox.attr('checked', !$checkbox.attr('checked'));
});
or:
$(".offer").on("click", function () {
var $checkbox = $(this).find(':checkbox');
$checkbox.attr('checked', !$checkbox.is(':checked'));
});
or, by directly manipulating the DOM 'checked' property (i.e. not using attr() to fetch the current state of the clicked checkbox):
$(".offer").on("click", function () {
var $checkbox = $(this).find(':checkbox');
$checkbox.attr('checked', !$checkbox[0].checked);
});
...and so on.
Note: since jQuery 1.6, checkboxes should be set using prop not attr:
$(".offer").on("click", function () {
var $checkbox = $(this).find(':checkbox');
$checkbox.prop('checked', !$checkbox[0].checked);
});
Another approach would be to extended jquery like this:
$.fn.toggleCheckbox = function() {
this.attr('checked', !this.attr('checked'));
}
Then call:
$('.offer').find(':checkbox').toggleCheckbox();
Warning: using attr() or prop() to change the state of a checkbox does not fire the change event in most browsers I've tested with. The checked state will change but no event bubbling. You must trigger the change event manually after setting the checked attribute. I had some other event handlers monitoring the state of checkboxes and they would work fine with direct user clicks. However, setting the checked state programmatically fails to consistently trigger the change event.
jQuery 1.6
$('.offer').bind('click', function(){
var $checkbox = $(this).find(':checkbox');
$checkbox[0].checked = !$checkbox[0].checked;
$checkbox.trigger('change'); //<- Works in IE6 - IE9, Chrome, Firefox
});
You could use the toggle function:
$('.offer').toggle(function() {
$(this).find(':checkbox').attr('checked', true);
}, function() {
$(this).find(':checkbox').attr('checked', false);
});
Why not in one line?
$('.offer').click(function(){
$(this).find(':checkbox').attr('checked', !$(this).find(':checkbox').attr('checked'));
});
I have a single checkbox named chkDueDate and an HTML object with a click event as follows:
$('#chkDueDate').attr('checked', !$('#chkDueDate').is(':checked'));
Clicking the HTML object (in this case a <span>) toggles the checked property of the checkbox.
jQuery: Best Way, delegate the actions to jQuery (jQuery = jQuery).
$( "input[type='checkbox']" ).prop( "checked", function( i, val ) {
return !val;
});
try changing this:
$(this).find(':checkbox').attr('checked', true );
to this:
$(this).find(':checkbox').attr('checked', 'checked');
Not 100% sure if that will do it, but I seem to recall having a similar problem. Good luck!
$('.offer').click(function(){
if ($(this).find(':checkbox').is(':checked'))
{
$(this).find(':checkbox').attr('checked', false);
}else{
$(this).find(':checkbox').attr('checked', true);
}
});
In JQuery I don't think that click() accepts two functions for toggling. You should use the toggle() function for that: http://docs.jquery.com/Events/toggle
$('.offer').click(function() {
$(':checkbox', this).each(function() {
this.checked = !this.checked;
});
});
Easiest solution
$('.offer').click(function(){
var cc = $(this).attr('checked') == undefined ? false : true;
$(this).find(':checkbox').attr('checked',cc);
});
<label>
<input
type="checkbox"
onclick="$('input[type=checkbox]').attr('checked', $(this).is(':checked'));"
/>
Check all
</label>
Another alternative solution to toggle checkbox value:
<div id="parent">
<img src="" class="avatar" />
<input type="checkbox" name="" />
</div>
$("img.avatar").click(function(){
var op = !$(this).parent().find(':checkbox').attr('checked');
$(this).parent().find(':checkbox').attr('checked', op);
});
$('controlCheckBox').click(function(){
var temp = $(this).prop('checked');
$('controlledCheckBoxes').prop('checked', temp);
});

Setting "checked" for a checkbox with jQuery

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?
Modern jQuery
Use .prop():
$('.myCheckbox').prop('checked', true);
$('.myCheckbox').prop('checked', false);
DOM API
If you're working with just one element, you can always just access the underlying HTMLInputElement and modify its .checked property:
$('.myCheckbox')[0].checked = true;
$('.myCheckbox')[0].checked = false;
The benefit to using the .prop() and .attr() methods instead of this is that they will operate on all matched elements.
jQuery 1.5.x and below
The .prop() method is not available, so you need to use .attr().
$('.myCheckbox').attr('checked', true);
$('.myCheckbox').attr('checked', false);
Note that this is the approach used by jQuery's unit tests prior to version 1.6 and is preferable to using $('.myCheckbox').removeAttr('checked'); since the latter will, if the box was initially checked, change the behaviour of a call to .reset() on any form that contains it – a subtle but probably unwelcome behaviour change.
For more context, some incomplete discussion of the changes to the handling of the checked attribute/property in the transition from 1.5.x to 1.6 can be found in the version 1.6 release notes and the Attributes vs. Properties section of the .prop() documentation.
Use:
$(".myCheckbox").attr('checked', true); // Deprecated
$(".myCheckbox").prop('checked', true);
And if you want to check if a checkbox is checked or not:
$('.myCheckbox').is(':checked');
This is the correct way of checking and unchecking checkboxes with jQuery, as it is cross-platform standard, and will allow form reposts.
$('.myCheckBox').each(function(){ this.checked = true; });
$('.myCheckBox').each(function(){ this.checked = false; });
By doing this, you are using JavaScript standards for checking and unchecking checkboxes, so any browser that properly implements the "checked" property of the checkbox element will run this code flawlessly. This should be all major browsers, but I am unable to test previous to Internet Explorer 9.
The Problem (jQuery 1.6):
Once a user clicks on a checkbox, that checkbox stops responding to the "checked" attribute changes.
Here is an example of the checkbox attribute failing to do the job after someone has clicked the checkbox (this happens in Chrome).
Fiddle
The Solution:
By using JavaScript's "checked" property on the DOM elements, we are able to solve the problem directly, instead of trying to manipulate the DOM into doing what we want it to do.
Fiddle
This plugin will alter the checked property of any elements selected by jQuery, and successfully check and uncheck checkboxes under all circumstances. So, while this may seem like an over-bearing solution, it will make your site's user experience better, and help prevent user frustration.
(function( $ ) {
$.fn.checked = function(value) {
if(value === true || value === false) {
// Set the value of the checkbox
$(this).each(function(){ this.checked = value; });
}
else if(value === undefined || value === 'toggle') {
// Toggle the checkbox
$(this).each(function(){ this.checked = !this.checked; });
}
return this;
};
})( jQuery );
Alternatively, if you do not want to use a plugin, you can use the following code snippets:
// Check
$(':checkbox').prop('checked', true);
// Un-check
$(':checkbox').prop('checked', false);
// Toggle
$(':checkbox').prop('checked', function (i, value) {
return !value;
});
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()
});
You can also extend the $.fn object with new methods:
(function($) {
$.fn.extend({
check : function() {
return this.filter(":radio, :checkbox").attr("checked", true);
},
uncheck : function() {
return this.filter(":radio, :checkbox").removeAttr("checked");
}
});
}(jQuery));
Then you can just do:
$(":checkbox").check();
$(":checkbox").uncheck();
Or you may want to give them more unique names like mycheck() and myuncheck() in case you use some other library that uses those names.
$("#mycheckbox")[0].checked = true;
$("#mycheckbox").attr('checked', true);
$("#mycheckbox").click();
The last one will fire the click event for the checkbox, the others will not.
So if you have custom code in the onclick event for the checkbox that you want to fire, use the last one.
To check a checkbox you should use
$('.myCheckbox').attr('checked',true);
or
$('.myCheckbox').attr('checked','checked');
and to uncheck a check box you should always set it to false:
$('.myCheckbox').attr('checked',false);
If you do
$('.myCheckbox').removeAttr('checked')
it removes the attribute all together and therefore you will not be able to reset the form.
BAD DEMO jQuery 1.6. I think this is broken. For 1.6 I am going to make a new post on that.
NEW WORKING DEMO jQuery 1.5.2 works in Chrome.
Both demos use
$('#tc').click(function() {
if ( $('#myCheckbox').attr('checked')) {
$('#myCheckbox').attr('checked', false);
} else {
$('#myCheckbox').attr('checked', 'checked');
}
});
This selects elements that have the specified attribute with a value containing the given substring "ckbItem":
$('input[name *= ckbItem]').prop('checked', true);
It will select all elements that contain ckbItem in its name attribute.
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);
I'm missing the solution. I'll always use:
if ($('#myCheckBox:checked').val() !== undefined)
{
//Checked
}
else
{
//Not checked
}
To check a checkbox using jQuery 1.6 or higher just do this:
checkbox.prop('checked', true);
To uncheck, use:
checkbox.prop('checked', false);
Here' s what I like to use to toggle a checkbox using jQuery:
checkbox.prop('checked', !checkbox.prop('checked'));
If you're using jQuery 1.5 or lower:
checkbox.attr('checked', true);
To uncheck, use:
checkbox.attr('checked', false);
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>
Here is code for checked and unchecked with a button:
var set=1;
var unset=0;
jQuery( function() {
$( '.checkAll' ).live('click', function() {
$( '.cb-element' ).each(function () {
if(set==1){ $( '.cb-element' ).attr('checked', true) unset=0; }
if(set==0){ $( '.cb-element' ).attr('checked', false); unset=1; }
});
set=unset;
});
});
Update: Here is the same code block using the newer Jquery 1.6+ prop method, which replaces attr:
var set=1;
var unset=0;
jQuery( function() {
$( '.checkAll' ).live('click', function() {
$( '.cb-element' ).each(function () {
if(set==1){ $( '.cb-element' ).prop('checked', true) unset=0; }
if(set==0){ $( '.cb-element' ).prop('checked', false); unset=1; }
});
set=unset;
});
});
Try this:
$('#checkboxid').get(0).checked = true; //For checking
$('#checkboxid').get(0).checked = false; //For unchecking
We can use elementObject with jQuery for getting the attribute checked:
$(objectElement).attr('checked');
We can use this for all jQuery versions without any error.
Update: Jquery 1.6+ has the new prop method which replaces attr, e.g.:
$(objectElement).prop('checked');
If you are using PhoneGap doing application development, and you have a value on the button that you want to show instantly, remember to do this
$('span.ui-[controlname]',$('[id]')).text("the value");
I found that without the span, the interface will not update no matter what you do.
Here is the code and demo for how to check multiple check boxes...
http://jsfiddle.net/tamilmani/z8TTt/
$("#check").on("click", function () {
var chk = document.getElementById('check').checked;
var arr = document.getElementsByTagName("input");
if (chk) {
for (var i in arr) {
if (arr[i].name == 'check') arr[i].checked = true;
}
} else {
for (var i in arr) {
if (arr[i].name == 'check') arr[i].checked = false;
}
}
});
Another possible solution:
var c = $("#checkboxid");
if (c.is(":checked")) {
$('#checkboxid').prop('checked', false);
} else {
$('#checkboxid').prop('checked', true);
}
As #livefree75 said:
jQuery 1.5.x and below
You can also extend the $.fn object with new methods:
(function($) {
$.fn.extend({
check : function() {
return this.filter(":radio, :checkbox").attr("checked", true);
},
uncheck : function() {
return this.filter(":radio, :checkbox").removeAttr("checked");
}
});
}(jQuery));
But in new versions of jQuery, we have to use something like this:
jQuery 1.6+
(function($) {
$.fn.extend({
check : function() {
return this.filter(":radio, :checkbox").prop("checked", true);
},
uncheck : function() {
return this.filter(":radio, :checkbox").prop("checked",false);
}
});
}(jQuery));
Then you can just do:
$(":checkbox").check();
$(":checkbox").uncheck();
If using mobile and you want the interface to update and show the checkbox as unchecked, use the following:
$("#checkbox1").prop('checked', false).checkboxradio("refresh");
For jQuery 1.6+
$('.myCheckbox').prop('checked', true);
$('.myCheckbox').prop('checked', false);
For jQuery 1.5.x and below
$('.myCheckbox').attr('checked', true);
$('.myCheckbox').attr('checked', false);
To check,
$('.myCheckbox').removeAttr('checked');
To check and uncheck
$('.myCheckbox').prop('checked', true);
$('.myCheckbox').prop('checked', false);
Be aware of memory leaks in Internet Explorer prior to Internet Explorer 9, as the jQuery documentation states:
In Internet Explorer prior to version 9, using .prop() to set a DOM
element property to anything other than a simple primitive value
(number, string, or boolean) can cause memory leaks if the property is
not removed (using .removeProp()) before the DOM element is removed
from the document. To safely set values on DOM objects without memory
leaks, use .data().
$('controlCheckBox').click(function(){
var temp = $(this).prop('checked');
$('controlledCheckBoxes').prop('checked', temp);
});
This is probably the shortest and easiest solution:
$(".myCheckBox")[0].checked = true;
or
$(".myCheckBox")[0].checked = false;
Even shorter would be:
$(".myCheckBox")[0].checked = !0;
$(".myCheckBox")[0].checked = !1;
Here is a jsFiddle as well.
Plain JavaScript is very simple and much less overhead:
var elements = document.getElementsByClassName('myCheckBox');
for(var i = 0; i < elements.length; i++)
{
elements[i].checked = true;
}
Example here
I couldn't get it working using:
$("#cb").prop('checked', 'true');
$("#cb").prop('checked', 'false');
Both true and false would check the checkbox. What worked for me was:
$("#cb").prop('checked', 'true'); // For checking
$("#cb").prop('checked', ''); // For unchecking
When you checked a checkbox like;
$('.className').attr('checked', 'checked')
it might not be enough. You should also call the function below;
$('.className').prop('checked', 'true')
Especially when you removed the checkbox checked attribute.
Here's the complete answer
using jQuery
I test it and it works 100% :D
// when the button (select_unit_button) is clicked it returns all the checed checkboxes values
$("#select_unit_button").on("click", function(e){
var arr = [];
$(':checkbox:checked').each(function(i){
arr[i] = $(this).val(); // u can get id or anything else
});
//console.log(arr); // u can test it using this in google chrome
});
In jQuery,
if($("#checkboxId").is(':checked')){
alert("Checked");
}
or
if($("#checkboxId").attr('checked')==true){
alert("Checked");
}
In JavaScript,
if (document.getElementById("checkboxID").checked){
alert("Checked");
}

Categories

Resources