JS method to clear text box content leaving to trigger js when restoring and mouse away from text box

  • 2020-11-30 08:10:31
  • OfStack

When the mouse clicks this text box, the default text inside can be cleared. When the input text is deleted and the focus leaves the text box, the default text will be written into the text box.

The code is as follows:


<!DOCTYPE html>
<html>
<head>
<meta charset=" utf-8">
<meta name="author" content="https://www.ofstack.com/" />
<title> Click the text box to clear the default values </title>
<script type="text/javascript"> 
window.onload=function()
{
var username=document.getElementById("username");
username.onclick=function()
{
if(username.value==" Please enter your name ")
{
username.value="";
this.focus();
}
}
username.onblur=function()
{
if(username.value=="")
{
username.value=" Please enter your name ";
}
}
}
</script>
</head>
<body>
<input type="text" value=" Please enter your name " id="username" />
</body>
</html> 

The above code realizes our requirements. When clicking the text box, it can clear the content in the text box. If the text box does not enter any content, when the mouse focus leaves the text box, the value of the text box will be restored to the default state. However, if the password box Ken is having trouble with because the password box is not shown in clear text, see the JavaScript Implementation input box (password box) section 1 for a solution.

Method to trigger js when the mouse leaves the text box


<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="textBox.WebForm1" %> 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head runat="server"> 
<title></title> 
<script type="text/javascript"> 
function validate() { 
var name = document.getElementById("txtName"); 
if (name.value == 2) { 
alert(" You must not be 2!"); 
name.focus(); 
return false; 
} 
return true; 
} 
</script> 
</head> 
<body> 
<form id="form1" runat="server"> 
<div> 
<asp:TextBox ID="txtName" onblur="validate();" runat="server" /> 
</div> 
</form> 
</body> 
</html> 

Related articles: