Checking if a checkbox is checked First, select the checkbox using a DOM method such as getElementById() or querySelector() . Then, access the checked property of the checkbox element. If its checked property is true , then the checkbox is checked; otherwise, it is not.
To check if an element is a checkbox: Use the tagName property to check if the value is an input element. Verify that the type property on the element has a value of checkbox . If both conditions are met, the element is a checkbox.
I would use .change()
and this.checked
:
$('#checkbox').change(function(){
var c = this.checked ? '#f00' : '#09f';
$('p').css('color', c);
});
--
On using this.checked
Andy E has done a great write-up on how we tend to overuse jQuery: Utilizing the awesome power of jQuery to access properties of an element. The article specifically treats the use of .attr("id")
but in the case that #checkbox
is an <input type="checkbox" />
element the issue is the same for $(...).attr('checked')
(or even $(...).is(':checked')
) vs. this.checked
.
Try this.
$('#checkbox').click(function(){
if (this.checked) {
$('p').css('color', '#0099ff')
}
})
Sometimes we overkill jquery. Many things can be achieved using jquery with plain javascript.
It may happen that "this.checked" is always "on". Therefore, I recommend:
$('#checkbox').change(function() {
if ($(this).is(':checked')) {
console.log('Checked');
} else {
console.log('Unchecked');
}
});
it's better if you define a class with a different colour, then you switch the class
$('#checkbox').click(function(){
var chk = $(this);
$('p').toggleClass('selected', chk.attr('checked'));
})
in this way your code it's cleaner because you don't have to specify all css properties (let's say you want to add a border, a text style or other...) but you just switch a class
I found out a crazy solution for dealing with this issue of checkbox not checked or checked here is my algorithm... create a global variable lets say var check_holder
check_holder has 3 states
If the checkbox is clicked,
$(document).on("click","#check",function(){
if(typeof(check_holder)=="undefined"){
//this means that it is the first time and the check is going to be checked
//do something
check_holder=1; //indicates that the is checked,it is in checked state
}
else if(check_holder==1){
//do something when the check is going to be unchecked
check_holder=0; //it means that it is not checked,it is in unchecked state
}
else if(check_holder==0){
//do something when the check is going to be checked
check_holder=1;//indicates that it is in a checked state
}
});
The code above can be used in many situation to find out if a checkbox has been checked or not checked. The concept behind it is to save the checkbox states in a variable, ie when it is on,off. i Hope the logic can be used to solve your problem.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With