How to create TextBox in ASP.NET with default text using jQuery

Leave a Comment

In this article, how to create a search box in ASP.NET with some default information text. The text is displayed only when the search box is out of focus.

Add a TextBox field with a Search button to the form as below:
<form id="form1" runat="server">
<p></p>
<div align="center">
<fieldset style="width:400px;height:80px;">
<p><asp:TextBox ID="TextBox1" width="200px" CssClass="defaultText" ToolTip="Enter your search keyword here" runat="server"></asp:TextBox>
<asp:Button ID="btnSubmit" Text="SEARCH" runat="server" /></p>
</fieldset>
</div>
</form>

We will now use jQuery to display the default text when the search box is out of focus.
<script type="text/javascript">
$(document).ready(function() {
var searchBox = $('#<%=TextBox1.ClientID%>');
searchBox.focus(
function() {
        if (searchBox.val() == this.title) {
searchBox.removeClass("defaultText");
searchBox.val("");
}
});
searchBox.blur(
function() {
if (searchBox.val() == "") {
searchBox.addClass("defaultText");
searchBox.val(this.title);
}
});
searchBox.blur();
});
</script> 

0 comments:

Post a Comment