asp.netでjqueryを使って検索ボックスのデフォルトのヒント機能を実現します。


テキストボックスで標準テキストヒントを作成します。
通常、ユーザはコンテンツを検索する時、テキストボックスにコンテンツを入力する前に、テキストボックスにデフォルトのヒントを与え、正しい内容を入力して検索するようにユーザに促す。
テキストボックスがフォーカスを得ると、テキストボックスの内容がヒントと同じであれば、ヒントの内容は自然に消えます。
テキストボックスの値がなく、フォーカスが失われた場合、テキストボックスの内容はデフォルトのヒントを再生成します。
上記の需要を実現するために、コードは以下の通りです。

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="Web.Default" %>

<!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 src="jquery-1.8.2.min.js" type="text/javascript"></script>
    <link href="Base.css" rel="stylesheet" type="text/css" />
    <style type="text/css">
        .text
        {
            border: #0a8fda solid 1px;
            color: #cccccc;
            font-style:italic;
            background: #fff url(img/input.gif);
            padding: 5px;
        }
        .text-focus
        {
            border: solid 1px #f50;
            background: #fff url(img/input.gif);
            padding: 5px;
        }
    </style>
    <script type="text/javascript">
        $(document).ready(function () {
            var txtSearch = $("#<%=txtSearch.ClientID%>");

            $("#txtSearch").focus(function () {
                if (txtSearch.val() == this.title) {
                    txtSearch.val("");

                    this.className = "text-focus";
                }
            });

            $("#txtSearch").blur(function () {

                if (txtSearch.val() == "") {
                    txtSearch.val(this.title);
                    this.className = "text";
                }
            });
            txtSearch.blur();
        });

    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div style="margin: 100px auto; width: 400px; height: 80px;border: solid 1px #0a8fda;">
        <p style="text-align:center;">
            <asp:TextBox ID="txtSearch" runat="server" Width="200px" class="text" ToolTip=" "></asp:TextBox>
            <asp:Button ID="btnSearch" runat="server" Text=" " class="button blue" />
        </p>
    </div>
    </form>
</body>
</html>