Last Updated : Jul 1, 2023
A boolean value indicating whether or not the checkbox is checked at the moment is returned by the "checked" attribute.
Simply set a checkbox's "checked" property to true to check it, and set it to false to uncheck it.
Additionally, event listeners can be used to determine when a checkbox's state has changed and to trigger the execution of a function or code block.
- The title of the web page is initially defined in the HTML code's <title> tag.
- The goal of the page is then explained in a <h2> heading and a <h4> subsection. A <input> element with the type attribute set to "checkbox" and the ID "checkbox" is defined below the subheading.
- We'll utilise this checkbox to show you how to see if it's checked or not.
- Next, a "text" ID is defined for a "<div>" element.
- The message that appears in this element will vary based on whether the checkbox is selected or not.
- The checkbox element is then given a call to the addEventListener() method, which keeps an eye out for a "change" event.
- Every time the user checks or unchecks the checkbox, this event is triggered.
- The arrow function in the event listener then determines whether the checkbox's "checked" attribute is true or false.
- If it is true, the string "Check box is checked" is set in the "text" div element's innerHTML property.
- If it is false, the "text" div element's innerHTML property is set to an empty string, thereby hiding any content that would have earlier been displayed.