YogeshChauhan.com
How to check if checkbox is checked or not using JavaScript?
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;
  }
}
dreamhost

Leave a Reply

Most Read

#1 How to set opacity or transparency using CSS? #2 Pagination in CSS with multiple examples #3 How to check if radio button is checked or not using JavaScript? #4 How to make HTML form interactive and using CSS? #5 How to uninstall Cocoapods from the Mac OS? #6 How to add Read More Read Less Button using JavaScript?



Recently Posted

Feb 24 How to modify the latest post array using get_posts() in WordPress? Feb 22 WordPress: How to get ACF field values from another post? Feb 22 WordPress: How to print ACF repeater field values? Feb 22 WordPress: How to print ACF array field values? Feb 21 WordPress: How to get field values in Advanced Custom Fields? Feb 21 WordPress: How to add a Search Icon in Menus with toggle effect using jQuery?



You might also like these

Values and Types Basics in JavaScriptJavaScriptObject destructuring in JavaScript: Unpacking fields from objects passed as function parameterJavaScript3 Common Usability Mistakes In Web DesignUI/UXHTML Copyright SymbolHTMLAccessing and Setting features of JavaScript ObjectsJavaScriptSorting Object Arrays in JavaScriptJavaScript