In the web application development, developers
always try to make UI more user-friendly and interactively. Showing watermark
on textbox is one of the tools to increase user-interactivity of website. Most
of the sites use the watermark mainly for “Search”
functionality. In this post I will show you a simple implementation of
watermark in textbox using JavaScript.
So, let’s start the watermark implementation
in textbox.
1- Aspx Page
<form id="form1" runat="server">
<div>
<asp:TextBox ID="txtWatermarkDemo"
runat="server"
CssClass="watermark"></asp:TextBox>
</div>
</form>2- CSS styles for watermark and simple textbox
<style type="text/css">
.watermark
{
font-style:italic;
font-size:12px;
color:#C0C0C0;
width:150px;
}
.textbox
{
font-style:normal;
font-size:12px;
color:#000000;
width:150px;
}
</style>
3- JavaScript Code for watermark
<script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script>
<script type="text/javascript">
//function to
remove the search keyword when focus is on textbox
function onFocusWatermark(txtid,strWatermark) {
var txtval = txtid.value;
if (txtval == strWatermark) {
$(txtid).addClass('textbox');
$(txtid).removeClass('watermark');
txtid.value = '';
}
}
//function to show
the search keyword when leave the textbox empty
function onBlurWatermark(txtid, strWatermark) {
var txtval = txtid.value;
if (txtval == '') {
$(txtid).removeClass('textbox');
$(txtid).addClass('watermark');
txtid.value = strWatermark;
}
}
</script>
4- Code behind
protected void Page_Load(object sender, EventArgs
e)
{
if (!IsPostBack)
{
string strSearch = "Search";
txtWatermarkDemo.Text
= strSearch;
txtWatermarkDemo.Attributes.Add("onFocus", "onFocusWatermark(this,'"
+ strSearch + "')");
txtWatermarkDemo.Attributes.Add("onBlur", "onBlurWatermark(this,'"
+ strSearch + "')");
}
}
In the code behind I have added onFocus and onBlur properties to asp.net textbox for referencing the relevant JavaScript
function.
Here you can see the complete implementation of
watermark in textbox.Happy coding!!
why no demo?
ReplyDelete