Check if a HTML checkbox is checked using JavaScript
Find out how to check if the checkbox is checked or not using JavaScript.
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:

Related Topics:
Change Background Color Using JavaScript
Related Posts
Copy text from an HTML element to clipboard-JavaScript
This article is about how to copy text from an html element to clipboard using JavaScript. You can copy from element with input field.
Disable scrolling Behaviour on a body with element on position fixed in mobile.
In this article we will learn on how to disable the scroll behaviour of a body on a element with position fixed on mobile devices..
How to change the color of <hr> tag using CSS
Here we will learn how to change the color or the background color of HR element in out html using css style.
Horizontal scrolling div with arrows using HTML and CSS
Tutorial on how to make horizontal scrolling div with arrows using html and css and for smooth scrolling we will use scrollBy() function in Javascript.
