0

我不明白为什么 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>

请有人帮助我!

4

2 回答 2

2

您正在分配而不是比较。

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

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

于 2013-04-18T10:04:02.837 回答
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>
于 2013-04-18T10:05:33.830 回答