YogeshChauhan . com

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;
  }
}
amazon

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 How to Use SQL MAX() Function with Dates? #6 PHP Login System using PDO Part 1: Create User Registration Page

Recently Posted

Jun 16 What are Stored Procedures for SQL Server? Jun 16 What are Class Constants in PHP? Jun 15 A short basic guide on states in React Jun 15 How to define constants in PHP? Jun 15 How to define visibility for a property in PHP? Jun 15 How to use @if and @else in SCSS?

You might also like these

How to Validate User Name, Email Address and URL in PHP?PHPA complete diagram with building blocks of an Angular applicationAngularRIGHT JOIN in PostgresPostgresWordPress: How to query all posts from custom post type and display them in a list?WordPressHow to create a simple tab interaction using CSS?CSSHow to Clone Objects in PHP?Misc