Skip to content

Checkbox checked JavaScript | HTML example code

  • by

How to check checkbox is checked or not in JavaScript?

A checked is Boolean property so you can directly use it in IF condition, whether a checkbox checked or not.

Example of checkbox checked JavaScript

Here is Html example code to Display Text when Checkbox is Checked or not checked on clicking the button.

<!DOCTYPE html>
<html>

<body>

    <input id="remember" name="remember" type="checkbox"/>
    <br>
    <button onclick="validate()" >Test Button for checkbox</button>

    <script type="text/javascript">
        function validate() {
            if (document.getElementById('remember').checked) {
                alert("Checked");
            } else {
                alert("You didn't check it!");
            }
        }
    </script>
</script>

</body>
</html>

Output:

Checkbox checked JavaScript

Note: Your script doesn’t know what the variable is if it placed after the script code. You need to get the element first using getElementById().

if checkbox is checked value=1 else 0 JavaScript

No JavaScript required, just put a hidden input before the checkbox:

<input type="hidden" name="check[0]" value="0" />
<input type="checkbox" name="check[0]" value="1" />

Do comment if you have any questions or suggestions on topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

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