Home > DeveloperSection > Articles > Implementing onblur event in Java Script

Implementing onblur event in Java Script


JavaScript JavaScript 
Ratings:
0 Comment(s)
 10021  View(s)
Rate this:

Implementing onblur event in Java Script

In this demonstration we learn how to implement onblur event in java script. We know that onblur event trigger any java script method when specified control where onblur event is registered is losing the focuses. Mainly we can us onblur event to implement validation feature in control. Following example demonstrate a concept of simple login form in which we implement validation of 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>

Output of the following code snippet is as follows

onblur event in Java Script

Create following java script function in 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>

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 value in text box.

onblur event in Java Script

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

onblur event in Java Script


Don't want to miss updates? Please click the below button!

Follow MindStick