Watermark in ASP.Net Textbox

Introduction

In this blog, I will explain how to create or set watermark text for textbox using JavaScript.

Description:

One day I got requirement like showing watermark text in textbox. To accomplish this task I used JavaScript functionality in my aspx page like this

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Watermark Textbox Using JavaScript</title>
<script language="javascript" type="text/javascript">
function WaterMark(txtName, event) {
var defaultText = "Enter Username Here";
// Condition to check textbox length and event type
if (txtName.value.length == 0 & event.type == "blur") {
//if condition true then setting text color and default text in textbox
txtName.style.color = "Gray";
txtName.value = defaultText;
}
// Condition to check textbox value and event type
if (txtName.value == defaultText & event.type == "focus") {
txtName.style.color = "black";
txtName.value = "";
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<b>UserName:</b>
<asp:TextBox ID="txtUserName" runat="server" Text="Enter Username Here" ForeColor="Gray" onblur ="WaterMark(this, event);" onfocus = "WaterMark(this, event);" />
</div>
</form>
</body>
</html>
Next Recommended Reading How to Set Watermark in ASP.NET TextBox