jQuery Select Box Validation

jQuery Select Box Validation

In this article, you will learn about the validation of select boxes. This is part of the jQuery validation series, which will show you how to validate select boxes. You will understand both single validation and dependent validation, where the selection of one select box may depend on another.

jQuery Validation

In single validation there is only one select box for which validation is done whether this select box has value or not. But in depend validation there are more than one select boxes in which on clicking the button it is validated whether all the select boxes have value or not.

Example: Suppose there are two select boxes in a form or the second select box is dependent on the first select box, then during the validation process it will be checked whether the first select box contains the key value or not.

Select Box Validation

             
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>RAYS CODING : Radio Button Validation</title>
        <link rel="stylesheet" href="../style.css">
        <script src="https://cdn.tailwindcss.com"></script>
    </head>
    <body class="bg-zinc-950 flex justify-center">
        <section class="w-auto h-auto mt-28 bg-white">
            <header class="bg-violet-600 p-5 pl-6 pr-6">
                <h2 class="text-3xl text-white tracking-wider">RAYS CODING : jQuery Select Box Validation</h2>
            </header>
            <form action="#" method="post" class="p-6 max-w-lg mx-auto bg-white rounded-lg shadow-lg">
                <label for="language" class="block text-xl font-semibold text-gray-700 mb-2">Language</label>
                <select name="language" id="language"
                    class="w-full px-4 py-2 border border-gray-300 focus:outline-none focus:ring-2 focus:ring-indigo-500">
                    <option value="">Select Language</option>
                    <option value="english">English</option>
                    <option value="hindi">Hindi</option>
                    <option value="french">French</option>
                    <option value="spanish">Spanish</option>
                </select>
                <div class="mt-5 bg-red-300 p-3 text-red-950 hidden" id="message">Please select a language!</div>
                <button type="submit" id="submit-button"
                    class="mt-5 bg-violet-600 p-3 w-full text-white font-semibold shadow-lg hover:bg-violet-700 focus:outline-none focus:ring-2 focus:ring-indigo-500 transition duration-300">
                    Submit
                </button>
            </form>
        </section>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"
            integrity="sha512-v2CJ7UaYy4JwqLDIrZUI/4hqeoQieOmAZNXBeQyjo21dadnwR+8ZaIJVT8EE2iyI61OV8e6M8PP2/4hpQINQ/g=="
            crossorigin="anonymous" referrerpolicy="no-referrer"></script>
    </body>
    </html>
                       

jQuery Validation

This HTML code creates a form in which the user has to select a language. The form has a dropdown menu with options of English, Hindi, French, and Spanish. If the user does not select a language and submits the form, an error message is displayed that says "Please select a language!". Has used Tailwind CSS to stylize the form and has also included jQuery for validation, but the validation code is yet to be written.

Validation In  jQuery

                   
    <script>
        $(document).ready(function () {
            $('#submit-button').on('click', function (e) {
                e.preventDefault();
                let language = $('#language').val();
                if (language == '') {
                    $('#message').removeClass('hidden bg-green-300 text-green-950')
                        .addClass('bg-red-300 text-red-950')
                        .text('Please select a language!')
                        .fadeIn().delay(3000).fadeOut(function () {
                            $(this).addClass('hidden');
                        });
                } else {
                    $('#message').removeClass('hidden bg-red-300 text-red-950')
                        .addClass('bg-green-300 text-green-950')
                        .text('You selected: ' + language + '.')
                        .fadeIn().delay(3000).fadeOut(function () {
                            $(this).addClass('hidden');
                        });
                }
            });
        });
    </script>
                   

This code checks if the user has selected a language when the button is clicked. If the user has not selected a language, an error message is shown which is in red color. If the language is selected, a success message is shown which is in green color, and the message is shown for 3 seconds.

jQuery Validation

It uses jQuery which changes the message dynamically when the button is clicked after the page loads. The FadeIn() and FadeOut() effects reveal and hide the message gradually, and delay(3000) allows the message to stay on the screen for 3 seconds.

Depended Select Box Validation

       
    <!DOCTYPE html>
    <html lang="en">

    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>RAYS CODING : Radio Button Validation</title>
        <link rel="stylesheet" href="../style.css">
        <script src="https://cdn.tailwindcss.com"></script>
    </head>

    <body class="bg-zinc-950 flex justify-center">
        <section class="w-auto h-auto mt-16 bg-white">
            <header class="bg-violet-600 p-5 pl-6 pr-6">
                <h2 class="text-3xl text-white tracking-wider">RAYS CODING : jQuery Select Box Validation</h2>
            </header>
            <form action="#" method="post" class="p-6 max-w-lg mx-auto bg-white rounded-lg shadow-lg">

                <!-- Gender Dropdown -->
                <label for="gender" class="block text-xl font-semibold text-gray-700 mb-2 mt-5">Gender</label>
                <select name="gender" id="gender"
                    class="w-full px-4 py-2 border border-gray-300 focus:outline-none focus:ring-2 focus:ring-indigo-500">
                    <option value="">Select Gender</option>
                    <option value="male">Male</option>
                    <option value="female">Female</option>
                    <option value="other">Other</option>
                </select>

                <!-- Age Input -->
                <label for="age" class="block text-xl font-semibold text-gray-700 mb-2 mt-5">Age</label>
                <select name="age" id="age"
                    class="w-full px-4 py-2 border border-gray-300 focus:outline-none focus:ring-2 focus:ring-indigo-500">
                    <option value="">Select Age Range</option>
                    <option value="18">18</option>
                    <option value="18to30">18 to 30</option>
                    <option value="31to40">31 to 40</option>
                    <option value="41to50">41 to 50</option>
                    <option value="51plus">51 and above</option>
                </select>

                <!-- Message (Validation feedback) -->
                <div class="mt-5 bg-red-300 p-3 text-red-950 hidden" id="message">Please select all fields!</div>

                <!-- Submit Button -->
                <button type="submit" id="submit-button"
                    class="mt-5 bg-violet-600 p-3 w-full text-white font-semibold shadow-lg hover:bg-violet-700 focus:outline-none focus:ring-2 focus:ring-indigo-500 transition duration-300">
                    Submit
                </button>
            </form>
        </section>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"
            integrity="sha512-v2CJ7UaYy4JwqLDIrZUI/4hqeoQieOmAZNXBeQyjo21dadnwR+8ZaIJVT8EE2iyI61OV8e6M8PP2/4hpQINQ/g=="
            crossorigin="anonymous" referrerpolicy="no-referrer"></script>

    </body>

    </html>
             

This HTML code creates a form with two dropdown menus. The first dropdown is for "Gender" which has the options: Male, Female, and Other. The second dropdown is for "Age" which has different age ranges, such as 18, 18-30, 31-40, 41-50, and 51+.

jQuery Validation

This form also has a submit button. If the user does not select either gender or age and clicks submit, an error message is displayed telling the user that both fields must be selected.

Depended On Validation In jQuery

                   
    <script>
        $(document).ready(function () {
            $('#submit-button').on('click', function (e) {
                e.preventDefault();

                let gender = $('#gender').val();
                let age = $('#age').val();

                if (gender === '' && age === '') {
                    $('#message').removeClass('hidden bg-green-300 text-green-950')
                        .addClass('bg-red-300 text-red-950')
                        .text('Please select both Gender and Age!')
                        .fadeIn().delay(3000).fadeOut(function () {
                            $(this).addClass('hidden');
                        });

                } else if (gender !== '' && age === '') {
                    $('#message').removeClass('hidden bg-green-300 text-green-950')
                        .addClass('bg-red-300 text-red-950')
                        .text('Please select your Age!')
                        .fadeIn().delay(3000).fadeOut(function () {
                            $(this).addClass('hidden');
                        });
                } else if (gender === '' && age !== '') {
                    $('#message').removeClass('hidden bg-green-300 text-green-950')
                        .addClass('bg-red-300 text-red-950')
                        .text('Please select your Gender!')
                        .fadeIn().delay(3000).fadeOut(function () {
                            $(this).addClass('hidden');
                        });

                } else {
                    $('#message').removeClass('hidden bg-red-300 text-red-950')
                        .addClass('bg-green-300 text-green-950')
                        .text('Form submitted successfully! You selected: Gender: ' + gender + ', Age: ' + age)
                        .fadeIn().delay(3000).fadeOut(function () {
                            $(this).addClass('hidden');
                        });
                }
            });
        });

    </script>
                   

This JavaScript/jQuery code is for form validation. When the user clicks on the "Submit" button of the form, this code will check if the user has selected gender and age. If both fields are not selected, an error message will be displayed. If both are selected, a message indicating successful submission of the form will be displayed.

jQuery Validation

Step-by-step explanation of the code:

  1. Button Click Event: When the user clicks on the "Submit" button, the #submit-button click event will be triggered.
  2. Gender and Age Check:
    1. If both fields (Gender and Age) are empty: A red error message will be displayed, saying "Please select both Gender and Age!"
    2. If only Gender is not selected: A red message will be displayed, saying "Please select your Gender!"
    3. If only Age is not selected: A red message will be displayed, saying "Please select your Age!"
    4. If both fields are selected: A green success message will be displayed saying "Form submitted successfully!" and this message will show the user which gender and age range he/she has selected.
    5. Fade-in and fade-out effect: The message will be displayed once for 3 seconds and then fade out.
jQuery Validation

Post a Comment

Previous Post Next Post

Recent in Technology