Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Execute a script when the element loses focus in HTML?
The onblur attribute in HTML is used to execute a JavaScript function when an element loses focus. This event is triggered when a user clicks outside the element, tabs to another element, or navigates away from the current input field.
Syntax
Following is the syntax for the onblur attribute −
<element onblur="function()">
The function() can be a JavaScript function name or inline JavaScript code that executes when the element loses focus.
Text Input with onblur
The most common use case is with form input fields where you want to validate or format data when the user finishes typing and moves to another field.
Example
Following example converts the input text to uppercase when the field loses focus −
<!DOCTYPE html>
<html>
<head>
<title>onblur Example</title>
</head>
<body style="font-family: Arial, sans-serif; padding: 20px;">
<p>Type text below and click outside the input field!</p>
<label for="myid">Country:</label>
<input type="text" name="myid" id="myid" onblur="display()" style="padding: 5px; margin: 10px;">
<script>
function display() {
var str = document.getElementById("myid");
str.value = str.value.toUpperCase();
}
</script>
</body>
</html>
When you type "india" and click outside the input field, it automatically changes to "INDIA" −
Type text below and click outside the input field! Country: [INDIA]
Input Validation with onblur
The onblur event is commonly used for form validation, checking if required fields are filled or if the input format is correct.
Example
Following example validates an email input field when it loses focus −
<!DOCTYPE html>
<html>
<head>
<title>Email Validation with onblur</title>
</head>
<body style="font-family: Arial, sans-serif; padding: 20px;">
<h2>Email Validation</h2>
<label for="email">Email:</label>
<input type="text" id="email" onblur="validateEmail()" style="padding: 5px; margin: 10px;">
<span id="message" style="color: red;"></span>
<script>
function validateEmail() {
var email = document.getElementById("email").value;
var message = document.getElementById("message");
var emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (email === "") {
message.textContent = "Email is required";
} else if (!emailPattern.test(email)) {
message.textContent = "Please enter a valid email";
} else {
message.textContent = "? Valid email";
message.style.color = "green";
}
}
</script>
</body>
</html>
The validation message appears when you move focus away from the email field −
Email Validation Email: [user@example.com] ? Valid email
Multiple Elements with onblur
You can apply the onblur attribute to multiple form elements to create a comprehensive validation system.
Example
Following example shows onblur validation for multiple input fields −
<!DOCTYPE html>
<html>
<head>
<title>Multiple onblur Events</title>
</head>
<body style="font-family: Arial, sans-serif; padding: 20px;">
<h2>Registration Form</h2>
<form>
<label for="username">Username:</label><br>
<input type="text" id="username" onblur="checkUsername()" style="padding: 5px; margin: 5px 0;">
<span id="usernameMsg"></span><br><br>
<label for="password">Password:</label><br>
<input type="password" id="password" onblur="checkPassword()" style="padding: 5px; margin: 5px 0;">
<span id="passwordMsg"></span>
</form>
<script>
function checkUsername() {
var username = document.getElementById("username").value;
var msg = document.getElementById("usernameMsg");
if (username.length < 3) {
msg.textContent = " ? Username must be at least 3 characters";
msg.style.color = "red";
} else {
msg.textContent = " ? Username looks good";
msg.style.color = "green";
}
}
function checkPassword() {
var password = document.getElementById("password").value;
var msg = document.getElementById("passwordMsg");
if (password.length < 6) {
msg.textContent = " ? Password must be at least 6 characters";
msg.style.color = "red";
} else {
msg.textContent = " ? Password strength is good";
msg.style.color = "green";
}
}
</script>
</body>
</html>
Each field validates independently when it loses focus, providing immediate feedback to users −
Registration Form Username: [john_doe] ? Username looks good Password: [????????] ? Password strength is good
Common Use Cases
The onblur attribute is commonly used for the following scenarios −
Form validation − Check if required fields are completed or if input format is correct.
Data formatting − Convert text to uppercase, lowercase, or proper case format.
Auto-save functionality − Save form data when users move between fields.
Field calculations − Calculate totals or perform mathematical operations based on input.
Real-time feedback − Provide immediate user feedback without form submission.
Conclusion
The onblur attribute is essential for creating interactive forms with real-time validation and user feedback. It executes JavaScript functions when elements lose focus, making it perfect for form validation, data formatting, and improving overall user experience. Use it with input fields, textareas, and other focusable elements to create responsive web applications.
