Luke Mat
Luke Mat

Reputation: 157

How to stop enter key from reloading page in a form in javascript

I have a search bar with a button that searches for stuff on another site. I got it to function correctly (it searches on the other site in a new tab) but anytime I click enter in the search bar, the page I'm on reloads. At first it reloaded from pressing enter and clicking search, then I changed the input type to button rather than submit. This took care of reloading when clicking on the button, but when the enter key is pressed the page reloads. Also, it only reloads if the search bar is clicked, not just at all times. The search bar has to be selected for the enter key to reload the page.

html:

<div id="search-3" class="widget widget_search">
    <h3 align="center">Search the other site!</h3>
    <form method="post" name="searchform" id="searchform">

      <span class="searching">
        <input type="text" value="" name="s" id="s" />
      </span>
      <input class="submit" type="button" Onclick="SearchBlog();" value="Search" />

    </form>
</div>

javascript:

function SearchBlog()
{
    var searchQuery = document.searchform.s.value;
    if(searchQuery != ""){
        var destination = "website.com/s" + searchQuery;
        window.open(destination, "_blank");
    }
}

I want to be able to use the enter key to search but I don't want it to reload the page.

Upvotes: 1

Views: 7343

Answers (2)

Shmiddty
Shmiddty

Reputation: 13967

Try this:

<input class="submit" type="button" Onclick="return SearchBlog();" value="Search" />

And

function SearchBlog()
{
    var searchQuery = document.searchform.s.value;
    if(searchQuery != ""){
        var destination = "website.com/s" + searchQuery;
        window.open(destination, "_blank");
    }
    return false;
}

Upvotes: 0

Barry Chapman
Barry Chapman

Reputation: 6780

Thats because you are submitting to a page that isn't there.

Use onsubmit in your <form> declaration instead:

<form method="POST" name="searchform" id="searchform" onsubmit="SearchBlog();">
   ...
</form>

Then make sure you return false; in your SearchBlog() function. And you should be good to go.

Upvotes: 3

Related Questions