Demig0d
Demig0d

Reputation: 158

window.location not working as expected

I have an asp.net web form with an html input and button at the top that I need to use as a search box. I need to integrate the template for the page with a page written in php so I'm trying to write the search box code as compatible with asp.net and php as I can.

That being said, I don't want the button to be a submit button since I don't want it to interfere with any buttons that appear on the page below it that might have to be submit buttons themselves.

When I click the Go button, everything works as expected. A lot of users, myself included, prefer to just hit the enter button and assume it will click the Go button. Since it is not a submit button this will not do, however when I hit return in the textbox, even with code in the onkeydown to run the search/redirect function, all it does is refresh the page.

Search box/button:

<input onkeydown="if (event.keyCode == 13) doSearch() " id="search" type="text" name="search" value="Search" style="width: 116px;" /><input id="btSearch" onclick="doSearch();" style="width: 33px; margin-left: 2px;" type="button" value="Go" />

Search function:

function doSearch() {
    var query = document.getElementById("search").value;
    window.location = "/Search.aspx?" + query;
}

What is intercepting my redirection to the search page when I hit enter?

Upvotes: 2

Views: 361

Answers (2)

xthexder
xthexder

Reputation: 1565

It's likely your forum is still being submitted. Add return false to cancel this:

<input onkeydown="if (event.keyCode == 13) ( doSearch(); return false; )" id="search" type="text" name="search" value="Search" style="width: 116px;" /><input id="btSearch" onclick="doSearch(); return false;" style="width: 33px; margin-left: 2px;" type="button" value="Go" />

You could also do it in an onsubmit handler to handle both with one call.

Upvotes: 0

daiscog
daiscog

Reputation: 12057

Can you post the whole form? The default action when you hit enter in a text field in most browsers is to submit the form, so your browser is submitting it after it calls the JS because your handler is not suppressing the default action. Add a return false to do so:

<input onkeydown="if (event.keyCode == 13) {doSearch(); return false; }" id="search" type="text" name="search" value="Search" style="width: 116px;" /><input id="btSearch" onclick="doSearch();" style="width: 33px; margin-left: 2px;" type="button" value="Go" />

Alternatively, just put the correct ACTION value in the form tag - otherwise the form will not work for users who do not have JavaScript!

Upvotes: 1

Related Questions