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?
This question is related to
javascript
jquery
checkbox
selected
checked
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');
}
});
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()
});
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");
}
$("#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.
You can try this:
$('input[name="activity[task_state]"]').val("specify the value you want to check ")
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.
Here is a way to do it without jQuery
function addOrAttachListener(el, type, listener, useCapture) {_x000D_
if (el.addEventListener) {_x000D_
el.addEventListener(type, listener, useCapture);_x000D_
} else if (el.attachEvent) {_x000D_
el.attachEvent("on" + type, listener);_x000D_
}_x000D_
};_x000D_
_x000D_
addOrAttachListener(window, "load", function() {_x000D_
var cbElem = document.getElementById("cb");_x000D_
var rcbElem = document.getElementById("rcb");_x000D_
addOrAttachListener(cbElem, "click", function() {_x000D_
rcbElem.checked = cbElem.checked;_x000D_
}, false);_x000D_
}, false);
_x000D_
<label>Click Me!_x000D_
<input id="cb" type="checkbox" />_x000D_
</label>_x000D_
<label>Reflection:_x000D_
<input id="rcb" type="checkbox" />_x000D_
</label>
_x000D_
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 overall:
$("#checkAll").click(function(){
$(".somecheckBoxes").prop('checked',$(this).prop('checked')?true:false);
});
In case you use ASP.NET MVC, generate many checkboxes and later have to select/unselect all using JavaScript you can do the following.
HTML
@foreach (var item in Model)
{
@Html.CheckBox(string.Format("ProductId_{0}", @item.Id), @item.IsSelected)
}
JavaScript
function SelectAll() {
$('input[id^="ProductId_"]').each(function () {
$(this).prop('checked', true);
});
}
function UnselectAll() {
$('input[id^="ProductId_"]').each(function () {
$(this).prop('checked', false);
});
}
Try this:
$('#checkboxid').get(0).checked = true; //For checking
$('#checkboxid').get(0).checked = false; //For unchecking
If you happen to be using Bootstrap (perhaps unawarely) ...
$('#myCheckbox').bootstrapToggle('on')
$('#myCheckbox').bootstrapToggle('off')
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($('jquery_selector').is(":checked")){_x000D_
//somecode_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
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
$('controlCheckBox').click(function(){
var temp = $(this).prop('checked');
$('controlledCheckBoxes').prop('checked', temp);
});
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()
});
$("#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 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);
Assuming that the question is...
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);
This may help someone.
HTML5
<input id="check_box" type="checkbox" onclick="handleOnClick()">
JavaScript.
function handleOnClick(){
if($("#check_box").prop('checked'))
{
console.log("current state: checked");
}
else
{
console.log("current state: unchecked");
}
}
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;
}
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');
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.
Here is a way to do it without jQuery
function addOrAttachListener(el, type, listener, useCapture) {_x000D_
if (el.addEventListener) {_x000D_
el.addEventListener(type, listener, useCapture);_x000D_
} else if (el.attachEvent) {_x000D_
el.attachEvent("on" + type, listener);_x000D_
}_x000D_
};_x000D_
_x000D_
addOrAttachListener(window, "load", function() {_x000D_
var cbElem = document.getElementById("cb");_x000D_
var rcbElem = document.getElementById("rcb");_x000D_
addOrAttachListener(cbElem, "click", function() {_x000D_
rcbElem.checked = cbElem.checked;_x000D_
}, false);_x000D_
}, false);
_x000D_
<label>Click Me!_x000D_
<input id="cb" type="checkbox" />_x000D_
</label>_x000D_
<label>Reflection:_x000D_
<input id="rcb" type="checkbox" />_x000D_
</label>
_x000D_
To check and uncheck
$('.myCheckbox').prop('checked', true);
$('.myCheckbox').prop('checked', false);
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.
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');
if($('jquery_selector').is(":checked")){_x000D_
//somecode_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
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");
You can use: .prop( propertyName ) - version added: 1.6
p {margin: 20px 0 0;}_x000D_
b {color: red;}_x000D_
label {color: red;}
_x000D_
<!doctype html>_x000D_
<html lang="en">_x000D_
<head>_x000D_
<meta charset="utf-8">_x000D_
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>_x000D_
</head>_x000D_
<body>_x000D_
_x000D_
<input id="check1" type="checkbox" checked="checked">_x000D_
<label for="check1">Check here</label>_x000D_
<p></p>_x000D_
_x000D_
<script>_x000D_
$( "input" ).change(function() {_x000D_
var $input = $( this );_x000D_
$( "p" ).html(_x000D_
"The .attr( \"checked\" ): <b>" + $input.attr( "checked" ) + "</b><br>" +_x000D_
"The .prop( \"checked\" ): <b>" + $input.prop( "checked" ) + "</b><br>" +_x000D_
"The .is( \":checked\" ): <b>" + $input.is( ":checked" ) + "</b>" );_x000D_
}).change();_x000D_
</script>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
In your .html file
<input type="checkbox" (change)="toggleEditable($event)">
In your .ts file
toggleEditable(event) {
if ( event.target.checked ) {
this.contentEditable = true;
}
}
In your .html file
<input type="checkbox" [(ngModel)]="isChecked" (change)="checkAction(isChecked ? 'Action1':'Action2')" />
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()
});
A JavaScript solution can be also simple and with less overhead:
document.querySelectorAll('.myCheckBox').forEach(x=> x.checked=1)
document.querySelectorAll('.myCheckBox').forEach(x=> x.checked=1)
_x000D_
checked A: <input type="checkbox" class="myCheckBox"><br/>_x000D_
unchecked: <input type="checkbox"><br/>_x000D_
checked B: <input type="checkbox" class="myCheckBox"><br/>
_x000D_
$(".myCheckBox").prop("checked","checked");
You can try this:
$('input[name="activity[task_state]"]').val("specify the value you want to check ")
I'm missing the solution. I'll always use:
if ($('#myCheckBox:checked').val() !== undefined)
{
//Checked
}
else
{
//Not checked
}
You can do this if you have the id to check it
document.getElementById('ElementId').checked = false
And this to uncheck
document.getElementById('ElementId').checked = true
This may help someone.
HTML5
<input id="check_box" type="checkbox" onclick="handleOnClick()">
JavaScript.
function handleOnClick(){
if($("#check_box").prop('checked'))
{
console.log("current state: checked");
}
else
{
console.log("current state: unchecked");
}
}
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);
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 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.
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;
}
}
});
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.
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;
}
}
});
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.
If you are using .prop('checked', true|false)
and don’t have changed checkbox, you need to add trigger('click')
like this:
// Check
$('#checkboxF1').prop( "checked", true).trigger('click');
// Uncheck
$('#checkboxF1').prop( "checked", false).trigger('click');
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;
});
});
$(".myCheckBox").prop("checked","checked");
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
Assuming that the question is...
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);
Another possible solution:
var c = $("#checkboxid");
if (c.is(":checked")) {
$('#checkboxid').prop('checked', false);
} else {
$('#checkboxid').prop('checked', true);
}
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.
$("#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.
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;
}
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
});
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).
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.
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;
});
Try this:
$('#checkboxid').get(0).checked = true; //For checking
$('#checkboxid').get(0).checked = false; //For unchecking
To check and uncheck
$('.myCheckbox').prop('checked', true);
$('.myCheckbox').prop('checked', false);
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.
Another possible solution:
var c = $("#checkboxid");
if (c.is(":checked")) {
$('#checkboxid').prop('checked', false);
} else {
$('#checkboxid').prop('checked', true);
}
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');
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()
});
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');
For overall:
$("#checkAll").click(function(){
$(".somecheckBoxes").prop('checked',$(this).prop('checked')?true:false);
});
I'm missing the solution. I'll always use:
if ($('#myCheckBox:checked').val() !== undefined)
{
//Checked
}
else
{
//Not checked
}
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;
});
});
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).
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.
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;
});
If you are using .prop('checked', true|false)
and don’t have changed checkbox, you need to add trigger('click')
like this:
// Check
$('#checkboxF1').prop( "checked", true).trigger('click');
// Uncheck
$('#checkboxF1').prop( "checked", false).trigger('click');
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.
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');
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');
A JavaScript solution can be also simple and with less overhead:
document.querySelectorAll('.myCheckBox').forEach(x=> x.checked=1)
document.querySelectorAll('.myCheckBox').forEach(x=> x.checked=1)
_x000D_
checked A: <input type="checkbox" class="myCheckBox"><br/>_x000D_
unchecked: <input type="checkbox"><br/>_x000D_
checked B: <input type="checkbox" class="myCheckBox"><br/>
_x000D_
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');
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().
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 case you use ASP.NET MVC, generate many checkboxes and later have to select/unselect all using JavaScript you can do the following.
HTML
@foreach (var item in Model)
{
@Html.CheckBox(string.Format("ProductId_{0}", @item.Id), @item.IsSelected)
}
JavaScript
function SelectAll() {
$('input[id^="ProductId_"]').each(function () {
$(this).prop('checked', true);
});
}
function UnselectAll() {
$('input[id^="ProductId_"]').each(function () {
$(this).prop('checked', false);
});
}
$("#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.
You can do this if you have the id to check it
document.getElementById('ElementId').checked = false
And this to uncheck
document.getElementById('ElementId').checked = true
$('controlCheckBox').click(function(){
var temp = $(this).prop('checked');
$('controlledCheckBoxes').prop('checked', temp);
});
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().
If you happen to be using Bootstrap (perhaps unawarely) ...
$('#myCheckbox').bootstrapToggle('on')
$('#myCheckbox').bootstrapToggle('off')
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");
}
You can check a checkbox checked condition using JavaScript in different ways. You can see below.
First method -
$('.myCheckbox').prop('checked', true);
Second method -
$('.myCheckbox').attr('checked', true);
Third method (for check condition if checkbox is checked or not) - $('.myCheckbox').is(':checked')
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();
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.
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');
You can check a checkbox checked condition using JavaScript in different ways. You can see below.
First method -
$('.myCheckbox').prop('checked', true);
Second method -
$('.myCheckbox').attr('checked', true);
Third method (for check condition if checkbox is checked or not) - $('.myCheckbox').is(':checked')
You can use: .prop( propertyName ) - version added: 1.6
p {margin: 20px 0 0;}_x000D_
b {color: red;}_x000D_
label {color: red;}
_x000D_
<!doctype html>_x000D_
<html lang="en">_x000D_
<head>_x000D_
<meta charset="utf-8">_x000D_
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>_x000D_
</head>_x000D_
<body>_x000D_
_x000D_
<input id="check1" type="checkbox" checked="checked">_x000D_
<label for="check1">Check here</label>_x000D_
<p></p>_x000D_
_x000D_
<script>_x000D_
$( "input" ).change(function() {_x000D_
var $input = $( this );_x000D_
$( "p" ).html(_x000D_
"The .attr( \"checked\" ): <b>" + $input.attr( "checked" ) + "</b><br>" +_x000D_
"The .prop( \"checked\" ): <b>" + $input.prop( "checked" ) + "</b><br>" +_x000D_
"The .is( \":checked\" ): <b>" + $input.is( ":checked" ) + "</b>" );_x000D_
}).change();_x000D_
</script>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
In your .html file
<input type="checkbox" (change)="toggleEditable($event)">
In your .ts file
toggleEditable(event) {
if ( event.target.checked ) {
this.contentEditable = true;
}
}
In your .html file
<input type="checkbox" [(ngModel)]="isChecked" (change)="checkAction(isChecked ? 'Action1':'Action2')" />
Source: Stackoverflow.com