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

0 Comments

Leave a reply

Your email address will not be published. required fields are marked *