简体   繁体   中英

Why do I get a "Cannot read property 'click' of null error

Inside the BODY tag:

<asp:Panel ID="nmSearch" CssClass="searchBox" runat="server" DefaultButton="HiddenSearchNM">
    <input type="text" runat="server" value="" placeholder="Search" id="searchB" class="styledTB searchB floatLeft" />
    <a href="JavaScript:void(0);" onclick="SearchNMClick();" title="Search" class="styledBtnSearch searchAnchor floatLeft defaultLinks">
        <asp:Image ImageUrl="~/images/searchWhite.png" CssClass="searchImg" runat="server" ToolTip="Search" AlternateText="Search" />
    </a>
    <asp:ImageButton ID="HiddenSearchNM" runat="server" CssClass="hideContent" ClientIDMode="Static" />
</asp:Panel>

Inside the HEAD tag:

<script>
function SearchNMClick() {
    document.getElementById('HiddenSearchNM').click();
}
</script>

I see the following error in the console:

Uncaught TypeError: Cannot read property 'click' of null
SearchNMClick
onclick

C# code behind which will fire off a search page from either Enter or click:

protected void HiddenSearchNM_Click(object sender, EventArgs e)
    {
        //MessageBox.Show("SEARCH NM");
        strSMain = searchB.Value;
        Response.Redirect("results.aspx?searchtext=" + strSMain +"&folderid=0&searchfor=all&orderby=title&orderdirection=ascending");
    }

But when I hit enter while in the textbox or the button click, I get the error above.

How do I resolve the error.

So weird, when I check the HTML source I see this (not sure why the ID is being changed):

<input type="image" name="ctl00$CUSTOM_Area_Top$HiddenSearchNM" id="ctl00_CUSTOM_Area_Top_HiddenSearchNM" class="hideContent" ClientIDMode="Static" src="" onclick="javascript:WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions(&quot;ctl00$CUSTOM_Area_Top$HiddenSearchNM&quot;, &quot;&quot;, true, &quot;&quot;, &quot;&quot;, false, false))" style="border-width:0px;" />

Use a Page directive to set static ids

<%@ Page ClientIDMode="static" %>

That should work with your id selector.

Also, check your rendered HTML for your ImageButton . If everything is setup correctly, it should preserve the ID .

You may change you JS function to:

function SearchNMClick() {
    document.getElementById('<%# HiddenSearchNM.ClientID %>').click();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM