How to Check Whether Checkbox is checked or not using Javascript
In this tutorial, We will learn how to check whether the checkbox is checked or not using Javascript.
First, create a checkbox using HTML
1 2 |
<input type="checkbox" id="mycheckbox" onclick="checkboxfunction()"> <p id="msg" style="display:none">Checkbox is CHECKED!</p> |
Now add Javascript for checking checkbox is checked or not.
1 2 3 4 5 6 7 8 9 10 11 |
<script> function checkboxfunction() { var checkBox = document.getElementById("mycheckbox"); var text = document.getElementById("msg"); if (checkBox.checked == true){ text.style.display = "block"; } else { text.style.display = "none"; } } </script> |
Here is the full code that we have written in this tutorial:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
<!DOCTYPE html> <html> <head> <title>Check Whether a Checkbox is Checked</title> </head> <body> <input type="checkbox" id="mycheckbox" onclick="checkboxfunction()"> <p id="msg" style="display:none">Checkbox is CHECKED!</p> <script> function checkboxfunction() { var checkBox = document.getElementById("mycheckbox"); var text = document.getElementById("msg"); if (checkBox.checked == true){ text.style.display = "block"; } else { text.style.display = "none"; } } </script> </body> </html> |
Demo