Aug
09
2007
A watermark texbox with JQuery and asp.net
Posted by admin under
Ajax
Finally I have managed to fix the search box here at aspcode.net. I upgraded CMS, changed the layout and everything but didn't manage to get everything up and running before by summer vacation. Anyway - have you tried the search box? It is one of those watermark textboxes - meaning it has a descriptive value (such as Search...) or a default value but when clicked (focused) it clears out. If the visitor doesn't write anything it goes back to the default value.
Anyway - while accomplishing it might not be too hard - there are lots of free javascripts for it available, just google - I still wanted to talk some about it cause it clearly shows the beauty of JQuery in particular and also how well JQuery and ASP.NET can play together.
Lets look at how the HTML code looked at before I added the feature:
Search: <asp:TextBox ID="txtInput" runat="server" CssClass="whatever" Text="Search..."></asp:TextBox>
Now as usual I look around the net to see if someone already has done it, trying to save me a few keystrokes. And indeed - Brian Reindel has a simple yet effective solution.
We just add an extra class tag to all input boxes we want to be used in this manner (in this example we have just a single input box, but the beauty of jquery os that you can work on multiple objects at a single statement, by using the foreach statement).
Search: <asp:TextBox ID="txtInput" runat="server" CssClass="whatever swap_value" Text="Search..."></asp:TextBox>
And last add the some code to the document ready handler activating the textbox improvement:
<head runat="server">
<title>Search textbox watermark</title>
<script type="text/javascript" src="jquery-113.pack.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
swapValues=[];
$(".swap_value").each(
function(i){
swapValues[i]=$(this).val();
$(this).focus(function()
{
if($(this).val()==swapValues[i])
{
$(this).val("")
}
}
).blur(function()
{
if($.trim($(this).val())=="")
{
$(this).val(swapValues[i])
}
}
)
}
)
}
);
</script>
</head>