Check if a HTML checkbox is checked using JavaScript

featured Image

If you are looking for “How do I check if a checkbox is checked in JavaScript?”

The simple answer is using checked property in JavaScript.

The checked is a boolean property that will return true if the checkbox is clicked and checked or else it will return false.

Let us see an example of how to use checked property in JavaScript.

First, let us make a checkbox in HTML with a label.

<input type="checkbox" id="checkedbox" />
<label for="">Agree to Terms and Conditions</label>

and we will have a Button with an id as “btn”.

<button id="btn">Submit</button>

And now we will write a JavaScript code where when the button is clicked , it will check if the checkbox in the HTML is checked or not.

If it’s checked it will alert as “Checked” or else it will alert “Not Checked“.

HTML Code :

 <form>
    <input type="checkbox" id="checkedbox" />
    <label>Agree to Terms and Conditions</label>
    <div>
      <button id="btn">Submit</button>
    </div>
</form>

Script:

const btn = document.querySelector("#btn");

btn.addEventListener("click", (e) => {
  e.preventDefault();
  validate();
});

function validate() {
  var checkedbox = document.getElementById("checkedbox");
  if (checkedbox.checked) {
    alert("Checked");
  } else {
    alert("Not Checked");
  }
}

In the script code, we have a function called validate(), which will run when we click the submit button.

Since checked is a boolean property, we can use it in any if..else condition. If the condition is true , it will alert “Checked”, if not it will alert “Not Checked”

Code Demo:

checkbox is checked

Edit v1kj3

Related Topics:

Change Background Color Using JavaScript

Copy Text From An HTML Element To Clipboard-JavaScript

Change Text Color Using JavaScript With Example

Related Posts

featured Image

Get the 10 characters from a string using JavaScript.

Here, in this article we will learn how to get the first 10 character from any string using JavaScript. Here we will be using JavaScript’s String method substring. What is…

Read more
featured Image

Convert date to long date format using JavaScript

In this article we will look into how to convert a date to a long date format using JavaScript. To convert it to a long format we will be using…

Read more
featured Image

Prevent body from scrolling when a modal is opened

Here, in this article, we will learn how to prevent the body from scrolling when a modal or a pop-up is opened using JavaScript. The scroll event is not cancelable….

Read more

Leave a Reply

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