为什么javascript忽略了文本框默认文本的变化?

时间:2013-04-18 09:45:54

标签: c# javascript asp.net dom

我无法理解为什么javascript会忽略文本框默认文本的更改?

更多细节: 文本框的默认文本为“搜索”。当客户端尝试使用默认文本提交搜索表单时,它应返回false并将焦点返回到文本框。

<asp:Panel CssClass="search rnd" ID="SearchBox" runat="server" DefaultButton="btnSearch">
    <asp:TextBox ID="txtSearch" runat="server" ValidationGroup="searchForm" MaxLength="100" CssClass="text" Text="Search" onfocus="if ( this.value == 'Search') { this.value = ''; }" onblur="if ( this.value == '' ) { this.value = 'Search'; }"></asp:TextBox>
    <asp:Button ID="btnSearch" runat="server" ValidationGroup="searchForm" CssClass="btn-search" ToolTip="Search the Website" OnClick="btnSearch_Click" OnClientClick="if ( document.getElementById('<%= txtSearch.ClientID %>').value = 'Search') { document.getElementById('<%= txtSearch.ClientID %>').style.background = 'yellow'; document.getElementById('<%= txtSearch.ClientID %>').focus(); return false; } " />
    <asp:RequiredFieldValidator CssClass="hdn rf" ID="RequiredFieldValidator1" ControlToValidate="txtSearch" runat="server" ErrorMessage="*"></asp:RequiredFieldValidator>
</asp:Panel>

请有人帮助我!

2 个答案:

答案 0 :(得分:2)

您要分配而不是比较。

更改:if ( document.getElementById('<%= txtSearch.ClientID %>').value = 'Search')

if ( document.getElementById('<%= txtSearch.ClientID %>').value == 'Search')

答案 1 :(得分:1)

您的代码运行良好,我只是将代码放在一个函数中并将其命名为OnClientClick

您还忘记在==声明中使用=代替if 试试这个:

   <asp:Panel CssClass="search rnd" ID="SearchBox" runat="server" DefaultButton="btnSearch">
    <asp:TextBox ID="txtSearch" runat="server" ValidationGroup="searchForm" MaxLength="100" CssClass="text" Text="Search"
     onfocus="if ( this.value == 'Search') { this.value = ''; }" onblur="if ( this.value == '' ) { this.value = 'Search'; }"></asp:TextBox>
    <asp:Button ID="btnSearch" runat="server" ValidationGroup="searchForm" CssClass="btn-search" ToolTip="Search the Website" 
    OnClick="btnSearch_Click" OnClientClick=" validateTextbox()" />
    <asp:RequiredFieldValidator CssClass="hdn rf" ID="RequiredFieldValidator1" ControlToValidate="txtSearch" runat="server"
     ErrorMessage="*"></asp:RequiredFieldValidator>
</asp:Panel>


<script>

    function validateTextbox() {

        if (document.getElementById('<%= txtSearch.ClientID %>').value == 'Search') {
            document.getElementById('<%= txtSearch.ClientID %>').style.background = 'yellow';

            document.getElementById('<%= txtSearch.ClientID %>').focus();

            return false;
        }

    }
</script>