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 Solution to the error “Visual Studio Code can’t be opened because Apple cannot check it for malicious software” #2 How to add Read More Read Less Button using JavaScript? #3 How to check if radio button is checked or not using JavaScript? #4 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #5 PHP Login System using PDO Part 1: Create User Registration Page #6 How to uninstall Cocoapods from the Mac OS?

Recently Posted

#Apr 8 JSON.stringify() in JavaScript #Apr 7 Middleware in NextJS #Jan 17 4 advanced ways to search Colleague #Jan 16 Colleague UI Basics: The Search Area #Jan 16 Colleague UI Basics: The Context Area #Jan 16 Colleague UI Basics: Accessing the user interface
You might also like these
6 Different Functions to Sort Arrays in PHPPHPWhat is Etrieve Flow?MiscellaneousHow to get the full URL of current page in PHP?PHPHow to zoom an element on hover using CSS?CSSWhat’s Interpolation in SCSS (Sass)?SCSSHow to verify your domain in Google Console with a TXT record?Miscellaneous