In JavaScript, if we write the following for example:
var c = this.checked;
What is checked
here? Is it just a state that tells us if a checkbox for example is checked or not? So, can we use it to check that the checkbox is also not checked?
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.
Check if a Single Check Box is Selected or not In this section, we will learn to check whether the checkbox is checked or not. In JavaScript, we can access the checkbox element using id, class, or tag name and apply '. checked' to the element, which returns either true or false based on the checkbox is checked.
The checked attribute is a boolean attribute. When present, it specifies that an <input> element should be pre-selected (checked) when the page loads. The checked attribute can be used with <input type="checkbox"> and <input type="radio"> . The checked attribute can also be set after the page load, with a JavaScript.
Assuming this
refers to a DOM element which has a checked
property (e.g. a checkbox or a radio button) then the checked
property will either be true
if the element is checked, or false
if it's not. For example, given this HTML:
<input type="checkbox" id="example">
The following line of JS will return false
:
var c = document.getElementById("example").checked; //False
Note that what you've written is standard JavaScript, not jQuery. If this
refers to a jQuery object rather than a DOM element, checked
will be undefined because the jQuery object does not have a checked
property. If this
is a jQuery object, you can use .prop
:
var c = this.prop("checked");
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