This tutorial will help you with JavaScript code with jQuery, which check that checkbox is checked or not and perform operations based on that. This useful before submitting any form to check if any checkbox is checked or not.
JavaScript Code :-
Below is the JavaScript code which check that checkbox (id: checkBox1) is selected or not. If checkbox is selected, it will unhide the element with id msgBox and that element will appear on page. If checkbox is not selected, it will hide the same element on page. Make sure you have included JQuery on your webpage.
1 2 3 4 5 6 7 8 9 | <script type="text/javascript"> if(document.getElementById('checkBox1').checked) { $("#msgBox").show(); } else { $("#msgBox").hide(); } </script> |
Demo URL :-
You can visit the following url to view demo for the same task. This demo used above JavaScript code to do it.
HTML Code :-
Below the sample html code used for creating this demo on above url. This code has a div (ID: msgBox) which appears on page if checkbox is checked and hide if checkbox is not checked.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | <html> <head> <script src="http://code.jquery.com/jquery-latest.js"></script> <script type="text/javascript"> function checkBoxDemo() { if(document.getElementById('checkBox1').checked) { $("#msgBox").show(); } else { $("#msgBox").hide(); } } </script> </head> <body> Demo - <input type="checkbox" id="checkBox1" onClick="checkBoxDemo()" /> <div id="msgBox" style="display:none">Checkbox checked &#9786;</div> </body> </html> |