articles

Implementing OnBlur event in Java Script

Implementing OnBlur event in Java Script

Anonymous User 18125 16-Mar-2011

Implementing OnBlur event in Java Script

In this Article, we'll learn how to implement onblur event in javascript. We know that onblur event triggers any javascript method when specified control where onblur event is registered is losing the focuses. Mainly we can use onblur events to implement the validation feature in control. The following example demonstrates a concept of a simple login form in which we implement validation of the text field.

Write down following code snippet in HTML document to create a user interface
<table style="border:3px double #cc3366;" cellpadding="0" cellspacing="0">
            <tr>
                <td>User Id</td>
                <td><input type="text" style="margin-left:30px;width:150px;margin-top:10px;margin-bottom:10px;" id="txtUserId" onblur="validateUserId()" /></td>
            </tr>
            <tr>
                <td>Password</td>
                <td><input type="password" id="txtPassword" style="margin-left:30px;width:150px;margin-top:5px;margin-bottom:10px;" onblur="validateUserPassword()" /></td>
            </tr>
            <tr>
                <td colspan="2">
                    <input type="button" onclick="alert('Login Successful')" value="Log In" style="margin:10px 10px 5px 5px" />
                </td>
            </tr>
</table>
The output of the following code snippet is as follows

Implementing OnBlur event in Java Script

Create the following javascript function in the head tag of HTML document
<script type="text/javascript">
        function validateUserId() {
            var uId = document.getElementById("txtUserId").value;
            if (uId.length == 0) {
                alert("User Id should not be empty");
            }
        }
 
        function validateUserPassword() {
            var uPassword = document.getElementById("txtPassword").value;
            if (uPassword.length == 0) {
                alert("User Password should not be empty");
            }
        }
</script>
The output of the above code snippet is as follows

As well as user select User Id text filed and changes the focus from that control without entering any value then an alert message is displayed for entering the value in the text box.

Implementing OnBlur event in Java Script

After entering values in User Id and password text field an alert message displayed for login successful.

Implementing OnBlur event in Java Script



Updated 14-Jul-2020
I am a content writter !

Leave Comment

Comments

Liked By