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.
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.
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>
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;
}
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);
}
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.
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.