Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript this.checked

Tags:

javascript

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?

like image 881
Simplicity Avatar asked Oct 06 '11 08:10

Simplicity


People also ask

How do you check if an element is checked JavaScript?

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.

What is checked in JavaScript?

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.

How do I show a checkbox as 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.


1 Answers

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");
like image 132
James Allardice Avatar answered Sep 18 '22 19:09

James Allardice