Yogesh Chauhan's Blog

How to check if checkbox is checked or not using JavaScript?

in JavaScript on November 14, 2020

Solution: We can use Input Checkbox checked Property to do so.


function check() {
  if (document.getElementById("checklist").checked == true) {
    console.log("checked");
  } else {
    console.log("not checked");
  }
}

Discussion

The checked attribute is a boolean attribute.

If you add it to the element then it will be pre-selected (checked) when the page loads.

Like this example:


<input type="checkbox" name="exam" value="Mid Term" checked>

The checked attribute can also be set after the page load, with a JavaScript.

Input Checkbox checked Property

We can make use of it and figure out whether use has clicked on it or not.

The checked property sets or returns the checked state of a checkbox. So, it reflects the HTML checked attribute.

It is supported in all major browsers.

Syntax


checkbox_object_name.checked

// this will return the checked property

checkbox_object_name.checked = true

// this will return the checked property to true

checkbox_object_name.checked = false

// this will return the checked property to false

And, true and false specifies whether a checkbox should be checked or not. So if we get true in return then it is checked and if we get false, then it is not checked.

We can also set it to checked using JavaScript

This function will toggle the checkbox.


function check() {
  if (document.getElementById("checklist").checked == true) {
    document.getElementById("checklist").checked = false;
  } else {
    document.getElementById("checklist").checked = true;
  }
}

Most Read

#1 How to check if radio button is checked or not using JavaScript? #2 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #3 How to add Read More Read Less Button using JavaScript? #4 How to uninstall Cocoapods from the Mac OS? #5 PHP Login System using PDO Part 1: Create User Registration Page #6 How to Use SQL MAX() Function with Dates?

Recently Posted

#Aug 15 Is PHP still good for back-end programming? #Aug 10 How to create a multisite network in WordPress? #Aug 3 How to create a circle that follows a cursor using JavaScript and CSS? #Aug 3 How to make a curtain slider using jQuery and CSS? #Aug 2 How to progressively load images and add a blurry placeholder? #Aug 1 How to create a placeholder loader (throbber) using CSS?
You might also like these
How to add Google Static Map using ACF map field?WordPressThe substr() method in JavaScript and how it’s different from substring()JavaScriptALTER DATABASE in PostgreSQLPostgresWhat is Prototypal Inheritance in JavaScript?JavaScriptHow does @extend rule work in SCSS (Sass)?SCSSHow to vertically and horizontally align text and image block (without flex or grid) in CSS?CSS