Javascript Form How to - Handle TextField focus lost event








Question

We would like to know how to handle TextField focus lost event.

Answer


 <!-- w  w  w  . j ava  2  s.c o  m-->

<html>
<head>
<script type="text/javascript" language="javascript">
function ChangeStatus(){
    console.log("focus lost");
    if (document.MyForm.MyTextField.value!==""){
        document.MyForm.Comments.readOnly = false;
        document.MyForm.Comments.select();
    } else{
        document.MyForm.MyTextField.focus();
    }
}
</script>
</head>
<body>
<table>
<form name="MyForm" action="" method="Post">
<tr>
 <td><input type="text" name="MyTextField" onblur="ChangeStatus()"/></td>
 <td>Enter your name</td>
</tr>
<tr>
 <td><textarea name="Comments" rows="6" cols="40">Please enter your name first</textarea></td>
 <td>Enter your comments.</td>
</tr>
<tr>
 <td><input type="submit" value="Click to Submit"/></td>
 <td>&nbsp;</td>
</tr>
</table>
</form>
</body>
</html>

The code above is rendered as follows: