window.location.href not working in Safari when using onkeypress

Posted by insanepaul on Stack Overflow See other posts from Stack Overflow or by insanepaul
Published on 2010-05-06T12:59:14Z Indexed on 2010/05/06 13:28 UTC
Read the original article Hit count: 341

Filed under:
|
|

I'm using an asp textbox and a search button. In Safari if I click the search button i get redirected to the search results page using javascript window.location.href. But strangely the same javascript will not redirect to the page if I press return in the textbox.

Using the alert function I can see that window.location.href has the the correct url and the location bar at the top changes from the search page(default.aspx) to the search results url however when I click OK to the alert box the url at the top reverts back to the default.aspx page. It works on ie7/8/firefox/chrome but not safari. Here is my javascript,cs and aspx code:

function submitSearchOnEnter(e) {

            var CodeForEnter = 13;
            var codeEnteredByUser;

            if (!e) var e = window.event;
            if (e.keyCode) codeEnteredByUser = e.keyCode;
            else if (e.which) codeEnteredByUser = e.which;

            if (codeEnteredByUser == CodeForEnter)
                RedirectToSearchPage();
        }

        function RedirectToSearchPage() {

            var searchText = $get('<%=txtHeaderSearch.ClientID%>').value

            if (searchText.length) {

                window.location.href = "Search.aspx?searchString=" + searchText;
            }
        }

protected void Page_Load(object sender, EventArgs e)
{
    txtHeaderSearch.Attributes.Add("onkeypress", "submitSearchOnEnter(event)");
}

<asp:Panel ID="pnlSearch" runat="server" DefaultButton="lnkSearch">
                <asp:TextBox ID="txtHeaderSearch" runat="server" CssClass="searchBox"></asp:TextBox>
                <asp:LinkButton ID="lnkSearch" OnClientClick="RedirectToSearchPage(); return false;"
                    CausesValidation="false" runat="server" CssClass="searchButton">
            SEARCH
                </asp:LinkButton>
            </asp:Panel>

I've tried return false; which doesn't allow me to enter any characters in the search box. I've spent ages online trying to find a solution. Maybe it has something to do with setTimeout or setTimeInterval but it didn't work unless i did it wrong.

© Stack Overflow or respective owner

Related posts about safari

Related posts about JavaScript