How to Check if Checkbox is Checked with JavaScript

Channel: Linux
Abstract: } else { $("script type="

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.

<script type="text/javascript"> if(document.getElementById('checkBox1').checked) { $("#msgBox").show(); } else { $("#msgBox").hide(); } </script>123456789<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.

Click to view demo >>

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.

<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 ☺</div> </body> </html>12345678910111213141516171819<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 ☺</div></body></html>

Ref From: tecadmin

Related articles