Select Box Validation Using JavaScript

Select Box Validation Using JavaScript

In our newest blog post, we'll guide you through the fundamentals of validating select boxes using JavaScript. Explore the core techniques for ensuring data accuracy and improving user interaction on your website. Whether you're a beginner or an experienced developer, mastering select box validation is key to maintaining data integrity and providing a seamless user experience. 

Select Box Validation Using JavaScript

Understanding the Importance of Select Box Validation

Imagine you have a form on your website where users need to select their country from a dropdown menu. Without validation, users might submit the form without making a selection, leading to incomplete or inaccurate data. Select box validation ensures that users provide the necessary information, improving data quality and user satisfaction.

Let's talk about select box validation using JavaScript.

GET SOURCE CODE

1. HTML structure


    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title></title>
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous">
        <link rel="stylesheet" href="style.css">
    </head>
    <body>
        <div class="container mt-5">
            <div class="row">
                <div class="col-lg-12">
                    <div class="card">
                        <div class="card-header wrapper">
                            <h3 class="title">Rays Coding :- JavaScript Validation</h3>
                        </div>
                        <div class="card-body">
                            <form action="" method="post">
                                <div class="row">
                                    <div class="col-lg-12">
                                        <div class="mb-3 field">
                                            <label for="country" class="form-label">Country Name</label>
                                            <select name="country" id="country" class="form-control">
                                                <option value="">Select Country</option>
                                                <option value="af">Afghanistan</option>
                                                <option value="au">Australia</option>
                                                <option value="br">Brazil</option>
                                                <option value="ca">Canada</option>
                                                <option value="de">Denmark</option>
                                                <option value="fr">France</option>
                                                <option value="ge">Germany</option>
                                                <option value="in">India</option>
                                                <option value="ja">Japan</option>
                                                <option value="un">United Kingdom</option>
                                            </select>
                                        </div>
                                    </div>
                                </div>
                                <div class="row error-row" id="errorRow" style="display: none;">
                                    <div class="col-lg-12">
                                        <div class="mb-3 field">
                                            <div class="alert alert-danger" id="error"></div>
                                        </div>
                                    </div>
                                </div>
                                <div class="row success-row" id="successRow" style="display: none;">
                                    <div class="col-lg-12">
                                        <div class="mb-3 field">
                                            <div class="alert alert-success" id="success"></div>
                                        </div>
                                    </div>
                                </div>
                                <div class="row">
                                    <div class="col-lg-12">
                                        <div class="field">
                                            <button type="button" class="btn btn-primary w-100" onclick="validation()">SUBMIT</button>
                                        </div>
                                    </div>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <script src="script.js"></script>
    </body>
    </html>

Select Box Validation Using JavaScript


This HTML code sets up a basic web page with a form for selecting a country. It includes Bootstrap for styling and a custom CSS file. The form contains a select dropdown for choosing a country, with options ranging from Afghanistan to the United Kingdom. Below the select dropdown, there are placeholders for displaying error and success messages, which are initially hidden. When the "SUBMIT" button is clicked, a JavaScript function called validation() is triggered. This function checks if a country is selected. If not, it displays an error message; otherwise, it shows a success message with the selected country. Additionally, there's a function to hide the error message after a short delay. The JavaScript code is included in an external file named script.js. Overall, this code creates a simple form with validation functionality using JavaScript.

2. CSS Styling


    @import url('https://fonts.googleapis.com/css?family=Poppins:400,500,600,700&display=swap');
    * {
        margin: 0;
        padding: 0;
        box-sizing: border-box;
        font-family: 'Poppins', sans-serif;
    }


    .card {
        width: 60%;
        margin: 10px auto;
    }

    .wrapper {
        background: #fff;
        border-radius: 15px;
        box-shadow: 0px 15px 20px rgba(0, 0, 0, 0.1);
        background: linear-gradient(-135deg, #c850c0, #4158d0);
    }

    .title {
        color: #fff;
        text-shadow: 0 0 10px #fff;
        text-align: center;
    }

    .field {
        height: 50px;
        width: 100%;
        margin-top: 20px;
        position: relative;
    }

    .field select.form-control,
    .field input.form-control {
        height: 100%;
        width: 100%;
        box-shadow: none;
        outline: none;
        font-size: 17px;
        padding-left: 20px;
        color: #4158d0;
        border: 1px solid lightgrey;
        transition: all 0.3s ease;
    }

    .field input.form-control:focus,
    .field input.form-control:valid {
        border-color: #4158d0;
    }

    .field label {
        color: #4158d0;
        font-weight: 400;
        font-size: 17px;
    }

    .field button {
        border: none;
        outline: none;
        background: linear-gradient(-135deg, #c850c0, #4158d0);
    }

    .error-row {
        display: none;
    }


3. JavaScript Validation Script


    // validation code
    function validation()
    {
        // get the input box value
        let inputVal = document.getElementById('country').value;
        let innnertextVal = document.getElementById('country').options[document.getElementById('country').selectedIndex].text;
        console.table('Name:- '+ inputVal);
        if(inputVal == '')
        {
            document.getElementById('error').innerText = "Please select a country.";
            document.getElementById('errorRow').style.display = 'block';
            hideError();
            return false;
        }
        else
        {
            document.getElementById('success').innerText = "You selected:- " +  innnertextVal ;
            document.getElementById('successRow').style.display = 'block';
            return true;
        }
    }
    // Hide Error Message
    function hideError()
    {
        setTimeout(function(){
            document.getElementById('errorRow').style.display ="none";
        }, 5000);
    }

Select Box Validation Using JavaScript

This JavaScript code provides validation functionality for the form in the HTML code snippet provided earlier. 

The `validation()` function is invoked when the "SUBMIT" button is clicked. It retrieves the value of the selected country from the dropdown menu (`<select>` element) using `document.getElementById('country').value`. Additionally, it retrieves the text of the selected option using `document.getElementById('country').options[document.getElementById('country').selectedIndex].text`

If no country is selected (i.e., the value is empty), it displays an error message ("Please select a country.") by setting the `innerText` property of an element with the ID `'error'`, and sets the display style of an element with the ID `'errorRow'` to `'block'` to make the error message visible. It then calls the `hideError()` function to hide the error message after a delay of 5 seconds.

Select Box Validation Using JavaScript

If a country is selected, it displays a success message ("You selected: [selected country]") by setting the `innerText` property of an element with the ID `'success'`, and sets the display style of an element with the ID `'successRow'` to `'block'` to make the success message visible.

The `hideError()` function is responsible for hiding the error message. It uses `setTimeout()` to delay execution by 5 seconds, then sets the display style of the error row to `'none'`, effectively hiding it.

Post a Comment

Previous Post Next Post

Recent in Technology