Checkbox Validation In jQuery

Checkbox Validation In jQuery

Hello, everyone! In this article,  I will explain to you "Checkbox Validation in jQuery". Today, we'll explore how to check whether checkboxes are ticked or not within an HTML form.

Checkbox Validation In jQuery main

Step of Name Validation

  1. Create a Checkbox form
  2. Write the Checkbox validation code

Create a Checkbox form

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Rays Coding-JQuery Validation</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-iYQeCzEYFbKjA/T2uDLTpkwGzCiq6soy8tYaI1GyVh/UjpbCx/TYkiZhlZB6+fzT" crossorigin="anonymous">
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <div class="container mt-5 form_box">
        <div class="row">
            <div class="card p-0">
                <div class="card-header bg-primary">
                    <h3 class="text-center text-white">Rays Coding :- JQuery Form Validation(Checkbox)</h3>
                </div>
                <div class="card-body">
                    <div class="row">
                        <div class="col-lg-12">
                            <form action="#" method="post" enctype="multipart/form-data">
                                <div class="row check_id">
                                    <div class="col-lg-6">
                                        <div class="mb-3">
                                            <div class="form-check">
                                                <input class="form-check-input  identity_class  identity" name="user_identity[]" type="checkbox" value="php" id="useridentity1">
                                                <label class="form-check-label ">PHP</label>
                                            </div>
                                            <div class="form-check">
                                                <input class="form-check-input  identity_class  identity" type="checkbox" name="user_identity[]" value="python" id="useridentity2">
                                                <label class="form-check-label ">Python</label>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="col-lg-6">
                                        <div class="mb-3">
                                            <div class="form-check">
                                                <input class="form-check-input  identity_class  identity" name="user_identity[]" type="checkbox" value="java" id="useridentity3">
                                                <label class="form-check-label ">Java</label>
                                            </div>
                                            <div class="form-check">
                                                <input class="form-check-input  identity_class  identity" name="user_identity[]" type="checkbox" value="javascript" id="useridentity4">
                                                <label class="form-check-label ">Javascript</label>
                                            </div>
                                        </div>
                                    </div>
                                    <span id="useridentity_error" class="useridentityerror"></span>
                                </div>
                                <div class="row">
                                    <div class="col-lg-4">
                                        <button type="submit" class="btn btn-primary mt-4" name="sub_btn" id="sub_button">Submit</button>
                                    </div>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div class="container">
        <div class="row">
            <div class="col-lg-12 validationtext">
                <h1>jQuery Checkbox Validation</h1>
            </div>
        </div>
    </div>
    <!-- jquery  CDN -->
    <script src="https://code.jquery.com/jquery-3.6.2.slim.min.js" integrity="sha256-E3P3OaTZH+HlEM7f1gdAT3lHAn4nWBZXuYe89DFg2d0=" crossorigin="anonymous"></script>
</body>
</html>

This HTML code is a webpage designed for validating checkboxes using jQuery. Similar to the previous example, it utilizes Bootstrap for styling and includes a form for users to select their preferred programming languages through checkboxes.

The structure of the webpage is quite similar to the email validation example. It contains a container for proper alignment and spacing, within which there's a card element acting as a container for the form. The card has a header with a blue background and a title indicating the purpose of the form, which is "Rays Coding: JQuery Form Validation(Checkbox)".

Within the card body, there's a form with multiple sets of checkboxes grouped by programming language categories. Each category is presented in a separate column for better organization. The checkboxes are labeled with the names of programming languages such as PHP, Python, Java, and JavaScript.

Below the checkboxes, there's an empty span element with an ID of "useridentity_error", presumably meant to display any validation errors related to checkbox selection.

At the bottom of the form, there's a submit button labeled "Submit" to initiate the validation process. Similar to the previous example, the form itself has no action attribute specified, meaning it doesn't submit the data anywhere upon submission.

Below the form, there's a separate section with the heading "jQuery Checkbox Validation", likely meant for providing additional information or instructions related to checkbox validation using jQuery.

Finally, the webpage includes a script tag importing jQuery from a Content Delivery Network (CDN), specifically version 3.6.2. This jQuery script will likely be used to implement the checkbox validation functionality, although the actual validation logic is not provided in this code snippet.

Write the Checkbox validation code

<script>
    $(document).ready(function () {
        $('#sub_button').on('click', function () {
            var field = $('input[type="checkbox"]').serializeArray();
            if (field.length == 0) {
                $('#useridentity_error').text('Please Select Any One Option.');
                $('#useridentity_error').css('color', 'red');
                return false;
            }
        });
    });
</script>

Checkbox Validation In jQuery main

This JavaScript code is designed to provide validation functionality for checkboxes using jQuery. It targets the submit button with the ID "sub_button" and attaches a click event handler to it. When the button is clicked, the function defined inside $(document).ready() is executed.

Within this function, the script retrieves all checkbox input fields using the jQuery selector $('input[type="checkbox"]').serializeArray(). This function serializes the selected checkboxes into an array of objects containing the names and values of the selected checkboxes.

The script then checks the length of the array. If it's zero, it means that no checkboxes have been selected, and thus, it displays an error message prompting the user to select at least one option. The error message is appended to the element with the ID "useridentity_error" and styled with red color for emphasis.

Finally, if no checkboxes are selected, the function returns false to prevent the form from being submitted. This effectively enforces the requirement for the user to select at least one checkbox option before proceeding with form submission.

Post a Comment

Previous Post Next Post

Recent in Technology