The onblur event triggers when an HTML element loses focus. This is common with input fields, textareas, dropdowns, or even links. When a user clicks or tabs away from a form element, the onblur event fires—allowing you to run JavaScript or jQuery-based validations.
✅ Why Use Onblur Validation?
Validating form fields on blur helps:
- Improve user experience with real-time feedback
- Prevent submitting empty or invalid data
- Auto-fill default values when needed
- Reduce server-side validation load
💡 Example Use Case: Restore a Default Value if Input Is Empty
Let’s say you want to display the default phrase “Search here…” when a user leaves a text input field blank. You can achieve this with a simple JavaScript onblur handler.
🧪 HTML + JavaScript Onblur Validation Code
<input type="text" id="mySearch" value="" onblur="restoreValue();" />
<script type="text/javascript">
function restoreValue() {
var currVal = document.getElementById('mySearch').value;
var defaultVal = 'Search here...';
if (currVal.trim() === '') {
document.getElementById('mySearch').value = defaultVal;
}
}
</script>
🔍 Code Explanation
- We assign the input field an
idofmySearch. - When the field loses focus (
onblur), it triggers therestoreValue()function. - Inside the function:
currValcaptures the current value of the field.defaultValholds our fallback string:'Search here...'.- If the current value is blank or just whitespace, we replace it with the default text.
🧩 jQuery Alternative for Onblur Validation
Prefer jQuery? Here’s how you can implement the same functionality:
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function() {
$('#mySearch').on('blur', function() {
var defaultVal = 'Search here...';
if ($(this).val().trim() === '') {
$(this).val(defaultVal);
}
});
});
</script>
🎯 Where to Use This Technique?
This type of onblur validation is useful in:
- Search boxes
- Contact forms
- Comment sections
- Custom form builders
- Any UI where guidance or placeholder text improves usability
📌 Final Thoughts
Using the onblur event for validation in JavaScript or jQuery is a simple yet powerful way to improve your form UX. Whether you’re restoring default values or checking for invalid input, this technique ensures smoother, more user-friendly interactions.
