Search code examples
windowlocationdocumentkeypressunbind

Can't unbind keypress; pressing 'enter' in searchbar passes the window.location/document.location I specified and goes to the wrong page


I'm working on a page that is part of a pre-existing site. There is some script attached to the page that is overriding my searchbar 'enter' presses, so that every time I press enter it goes to the site-search page instead of my events-search page. This is my function:

$(".searchBox").keypress(function (e) {
    var key = e.which;
    if (key == 13) // the enter key code
    {
        var searchTerms = $(this).val();
        var newQueryString = updateQueryStringParameter(resetPage(document.URL), "q", searchTerms);
        window.location.href = newQueryString;
    }
});

By stepping through it, I can see that it is hitting each line of my method, including window.location.href... but then it keeps going, and loads the wrong page even though newQueryString is correct.

I tried using document.location isntead of window.location.href, and I tried unbinding my searchbox

$(document).ready(function () {
    $(".searchBox").unbind();
}

but it didn't work...


Solution

  • You can use preventDefault() method to stop the default event propagation.

        $("#myForm").submit(function(event){
               event.preventDefault();
       });
    

    http://api.jquery.com/event.preventdefault/