Check Box Validation in JavaScript

To implement checkbox validation in a web form, you typically want to ensure that at least one checkbox is selected before allowing the form to be submitted.

<!DOCTYPE html>
<html lang="en">
   <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>Newsletter Form</title>
      <style>
         .error {
         display: none; /* Hidden by default */
         color: red;
         font-family: Arial, sans-serif;
         }
         .show {
         display: block; /* Show the error message */
         }
      </style>
   </head>
   <body>
      <form id="newsletterForm" action="22.php" method="POST" onsubmit="return validateForm()">
         <div>
            <input type="checkbox" name="send_newsletter[]" />
            <label for="send_newsletter_1">Send me your newsletter</label>
            <input type="checkbox" name="send_newsletter[]" />
            <label for="send_newsletter_2">Send me your newsletter</label>
         </div>
         <div>
            <span id="error" class="error">Please select at least one option.</span>
            <input type="submit" name="submit" value="Submit" />
         </div>
      </form>
      <script>
         function validateForm() {
             const checkboxes = document.querySelectorAll('input[name="send_newsletter[]"]');
             const isChecked = Array.from(checkboxes).some(checkbox => checkbox.checked);
             
             const errorElement = document.getElementById('error');
             
             if (!isChecked) {
                 errorElement.classList.add('show');
                 return false; // Prevent form submission
             }
             
             // Hide error message if form is valid
             errorElement.classList.remove('show');
             return true; // Allow form submission
         }
      </script>
   </body>
</html>

administrator

Leave a Reply

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