How to Call the Javascript Function When a Checkbox is Checked or Unchecked?

In this article, we call a Javascript function when a checkbox is checked or unchecked.

Generally, this task is necessary when we want to check some condition when a Checkbox is Checked Unchecked?

HTML

<!DOCTYPE html>
<html>
   <head>
      <title>Display Data in Textarea</title>
   </head>
   <body>
      
      <label for="male">Male</label>
      <input type="checkbox" name="gender" id="male" onclick="stickyheaddsadaer()"/>
        
      <label for="male">Female</label>
      <input type="checkbox" name="gender" id="female" onclick="stickyheaddsadaer()"/>
     
        
   </body>
</html>

Javascript

function stickyheaddsadaer() {

        
       // Do your calculation here.

        alert("Hello, Coder");

   }

How to get checkbox value in javascript

Here is the simple code to get the checkbox value in javascript, You just need to add class in the checkbox and add some extra simple js code.

HTML

<!DOCTYPE html>
<html>
   <head>
      <title>Display Data in Textarea</title>
   </head>
   <body>
      
      <label for="male">Male</label>
      <input type="checkbox" class="messageCheckbox" value="male" name="gender" id="male" onclick="stickyheaddsadaer()"/>
        
      <label for="male">Female</label>
      <input type="checkbox"class="messageCheckbox" value="female" name="gender" id="female" onclick="stickyheaddsadaer()"/>
     
        
   </body>
</html>

Javascript

function stickyheaddsadaer() {

var checkedValue = document.querySelector('.messageCheckbox:checked').value;
        alert(checkedValue);

   }

The Document method querySelector() returns the first Element within the document that matches the specified selector, or group of selectors. If no matches are found, null is returned.

I hope this post will be helpful for you.