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");
}
Ok, I've been coding a website for a while now and this the first "insurmountable" problem I haven't found an aswer for, so now I'm turning to you, the experts.
On my form I have three drop-down menus, one textbox and one disabled checkbox. I want it to work so that when a user has selected an option from each drop-down menu and written something on the textbox, the checkbox becomes enabled.
I have found this code when I have been looking for a solution and it's very similar to my problem. However, when I try to add another drop-down menu, it still enables the button when I select an option from the first menu and completely ignores the second menu. I'm sorry, I'm new to Jquery/JavaScript and I just think it should work that way when the class names are same on both menus (jQuery class selector: ('.dropdown')).
I have also found a similar code with textboxes. I just don't know how to combine these codes so it would act the way I want.
See it here: http://jsfiddle.net/JKmkL/109/
$(document).ready(function() {
$('.required').change(function() {
var done=true;
$('.required').each(function(){
if(!$(this).val()){
$('.myCheckBox').prop('disabled',true);
done=false;
return false;
}
});
if(done){$('.myCheckBox').prop('disabled',false);}
});
});
And add class required to the elements.
Edit:
The code above assumes that the default <option> has value="". If not, you can use http://jsfiddle.net/JKmkL/114/
$(document).ready(function() {
$('.required').change(function() {
var done=true;
function quit(){
$('.myCheckBox').prop('disabled',true);
done=false;
return false;
}
$('.required.dropdown').each(function(){
if($(this).children(':selected').hasClass("disablenext")){
return quit();
}
});
$('.required[type=text]').each(function(){
if(!$(this).val()){
return quit();
}
});
if(done){$('.myCheckBox').prop('disabled',false);}
});
});
Edit 2:
If you want to show a div when the checkbox is checked and hide it when the checkbox is disabled, use
JavaScript:
$(document).ready(function() {
$('.required').change(function() {
var done=true;
function quit(){
$('.myCheckBox').prop('disabled',true).removeAttr('checked');
done=false;
$('#div2').addClass('hide');
return false;
}
$('.required.dropdown').each(function(){
if($(this).children(':selected').hasClass("disablenext")){
return quit();
}
});
$('.required[type=text]').each(function(){
if(!$(this).val()){
return quit();
}
});
if(done){$('.myCheckBox').prop('disabled',false);}
});
$('.myCheckBox').click(function(){
$('#div2')[(this.checked?'remove':'add')+'Class']('hide');
});
});
CSS:
.hide{display:none}
See it here: http://jsfiddle.net/JKmkL/133/
I assume that dropdown's default value is value=""
$('#form_submit_button').click(function(){
$('.checkbox').attr('disabled',true);
var all_selected = true;
$('.dropdown').each(function(){
if(!$(this).val())
{
all_selected = false;
}
});
if(!$('#text_box').text())
{
all_selected = false;
}
if(all_selected)
{
$('.checkbox').attr('disabled',false);
}
});
First of all, say the id for the three dropdowns are called d1, d2, and d3; textbox is txt; and checkbox is chk. You can then define a function that determines when the checkbox must be enabled:
function shouldEnableCheckbox() {
var nonEmptyFields = $("#d1,#d2,#d3,#txt").filter(function() {
return this.value;
});
return nonEmptyFields.length == 4;
}
Essentially, you select all 4 elements, filter those that are non-empty, and compare the resulting filtered array with 4. If it is true, it means you should enable the checkbox.
Then, assign the change event handler to all 4 elements, invoke the previous function, and assign the result to the disabled property of the checkbox:
$("#d1,#d2,#d3,#txt").change(function() {
$("#chk").prop("disabled", !shouldEnableCheckbox());
});
Here's the working DEMO, and another working, more generic DEMO, which uses a class instead of ids to identify the required elements.
How can I retrieve the new selected value and the previous selected value with JavaScript when onChange or similar event is called?
<select size="1" id="x" onchange="doSomething()">
<option value="47">Value 47</option>
...
function doSomething() {
var oldValue = null; // how to get the old value?
var newValue = document.getElementById('x').selected.value;
// ...
Thank you! :)
Using straight JavaScript and DOM, something like this (live example):
var box, oldValue;
// Get a reference to the select box's DOM element.
// This can be any of several ways; below I'll look
// it up by ID.
box = document.getElementById('theSelect');
if (box.addEventListener) {
// DOM2 standard
box.addEventListener("change", changeHandler, false);
}
else if (box.attachEvent) {
// IE fallback
box.attachEvent("onchange", changeHandler);
}
else {
// DOM0 fallback
box.onchange = changeHandler;
}
// Our handler
function changeHandler(event) {
var index, newValue;
// Get the current index
index = this.selectedIndex;
if (index >= 0 && this.options.length > index) {
// Get the new value
newValue = this.options[index].value;
}
// **Your code here**: old value is `oldValue`, new value is `newValue`
// Note that `newValue`` may well be undefined
display("Old value: " + oldValue);
display("New value: " + newValue);
// When done processing the change, remember the old value
oldValue = newValue;
}
(I'm assuming all of the above is inside a function, like a page load function or similar, as in the live example, so we're not creating unnecessary global symbols [box, oldValue, 'changeHandler`].)
Note that the change event is raised by different browsers at different times. Some browsers raise the event when the selection changes, others wait until focus leaves the select box.
But you might consider using a library like jQuery, Prototype, YUI, Closure, or any of several others, as they make a lot of this stuff a lot easier.
Look here: Getting value of select (dropdown) before change
I think the better,
(function () {
var previous;
$("select").focus(function () {
// Store the current value on focus, before it changes
previous = this.value;
}).change(function() {
// Do something with the previous value after the change
alert(previous);
});
})();
The following code snippet may help
<html>
<script type="text/javascript">
this.previousVal;
function changeHandler(selectBox)
{
alert('Previous Val-->'+selectBox.options[this.previousVal].innerHTML)
alert('New Val-->'+selectBox.options[selectBox.selectedIndex].innerHTML)
this.previousVal=selectBox.selectedIndex;
}
</script>
<body>
<select id="selectBox" onchange="changeHandler(this)">
<option>Sunday</option><option>Monday</option>
<option>Tuesday</option><option>Wednesday</option>
</select>
<script type="text/javascript">
var selectBox=document.getElementById("selectBox")
this.previousVal=selectBox.selectedIndex
</script>
<body>
</html>
Below worked for me.
Add below two events to your select HTML tag:-
onFocus='this.oldValue = this.value'; //if required in your case add this line to other events like onKeyPressDown and onClick.
onChange = 'alert(this.oldValue); this.value=this.oldValue'